function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Mohammed AzarudeenMohammed Azarudeen 

How to Download PDF Without Adding to Notes and Attachment

My custom object name is Patient__c
On the List View I have Download button to download the PDF(VFP rendered as PDF)
Here, before downloading am adding the pdf to notes and attachments and then downloading.
Now I dont want to store to notes and attachments and it should store programatically(like storing to variable) and should download from there.
How to achieve this.
Any help is appreciable thanks!!
Code :
global class DownloadPatient 
 // Receive Attachments info from Attachment ParentId
   private static String API_STATUS_NORMAL = '200';
   webService static string getAttachmentByParentId(string sfdcId)
         List<id> ids = new List<id>();
         if(string.isempty(sfdcId))  {
            return DownloadPatientResponse.errorJson('Parameter sfdcId is required.');
        string[] idsArray = sfdcId.split(',');
        for(integer i=0; i<idsArray.size();i++)
        // Added this code to restrict batch download for some of the accounts who all are having uncheck for this field  Print_Patient__c
        List<Patient__c> invList = New List<Patient__c>();
        invList = [Select id, name, Print_Patient__c, from Patient__c where ID IN: ids];
        List<Attachment> attInsert = new List<Attachment>();
        if(invList.size() > 0){
            System.debug(' ====> invList size <==== ');
            for(Patient__c invc : invList){
                System.debug(' ====> Patient is : <==== ' + invc);
                String msg = 'Selected invoices are not eligible for Patient Printing, please check the Account ';
                if(invc.Print_Patient__c == false){
                    System.debug(' ====> invc.Print_Patient__c value false <==== ');
                    return DownloadPatientResponse.errorJson( msg );
                PageReference pdf = new PageReference('/apex/PatienDetails?id=';
                Attachment attach = new Attachment();
                if (attach == null) attach = new Attachment();
                Blob body;
                try {
                        System.debug(' ==> as Test Class <== ');
                        body = Blob.valueOf('Some Text');
                        System.debug(' ==> as Apex normal Class <== ');
                        body = pdf.getContentAsPDF();   
                catch (VisualforceException e) {
                    String msg2 = e.getMessage();
                    return DownloadPatientResponse.errorJson( msg2 );
                attach.Body = body;
       +'_Patient_'+ Datetime.Now() +'.PDF';
                attach.IsPrivate = false;
                attach.ParentId =;
                attach.contentType = 'application/pdf';
        Insert attInsert;
        integer totalSizeOfFiles=0;
        integer totalSizeAnPatient=0;
        String invoiceId='';
        set<String> remainingsIdsSet=new set<String>();
        List<attachment> attachmentList = new List<attachment>();
          //for(attachment att:[select ParentId,id,Name,Body,contenttype from attachment where ParentId IN:ids]) {
          for(attachment att: attInsert) {          
                integer eachFileSize=att.Body.size();
                String parentId=att.ParentId;
                    System.debug('--ID: ''. ParentId: '+parentId+'. FileSize: '+eachFileSize+'. TotalPatientSize: '+totalSizeAnPatient);
                }else if(invoiceId.equals(parentId)){
                    System.debug('--ID: ''. ParentId: '+parentId+'. FileSize: '+eachFileSize+'. TotalPatientSize: '+totalSizeAnPatient);
                if(eachFileSize<4500000 && totalSizeAnPatient<4500000){
                    System.debug('--ID: '+parentId+'. FileSize: '+eachFileSize+'. TotalFileSize: '+totalSizeOfFiles+'. HeapSize: '+Limits.getHeapSize());
                    if(totalSizeOfFiles>= 4500000){
                          System.debug('--Adding to RemIDs ID: '+parentId+'. FileSize: '+eachFileSize);
             String remainingIds=null;
             List<String> remainingIdList=new List<String>(remainingsIdsSet);
             for(integer i=0;i<remainingIdList.size();i++){
             List<Object> dataList = new List<Object>();
             for(Attachment at :attachmentList)
                Map<String, String> atMap = new Map<String, String>();
                atMap.put( 'Name', at.Name );
                atMap.put( 'Body', EncodingUtil.base64Encode( at.body ));
                datalist.add( atMap );
                 Map<String, Object> response = new Map<String, Object>();
                 response.put('status', API_STATUS_NORMAL);
                 if( datalist != null ){
                     response.put('id', remainingIds);
                 return json.serialize( response );
         // Save Zip file to Document
   webService static String saveToDocument( String zipFileData, String fileName ){
            String userId = UserInfo.getUserId();
            List<Document> docList = [SELECT Id, Name, FolderId, Body FROM Document WHERE Name = :fileName AND FolderId = :userId];
            Document doc = new Document();
            if( docList == null || docList.size() == 0 ) {
                doc.Name = fileName;
                doc.FolderId = UserInfo.getUserId();
                doc.Body = EncodingUtil.base64Decode( zipFileData );
                System.debug(' Insert Doc @@@@ ' + doc);
                insert doc;
            else {
                doc = docList.get(0);
                doc.Body = EncodingUtil.base64Decode( zipFileData );
                update doc;
            System.debug('--ZipFileName: '+fileName+'. DocId: '+doc.Id);
            return DownloadPatientResponse.normalJson( doc.Id );
        } catch ( Exception ex ) {
            return DownloadPatientResponse.errorJson( ex.getMessage() );

If you have VF page which is rendered as PDF, It should work for you? I am not sure what is the issue you are facing there. 
Mohammed AzarudeenMohammed Azarudeen
Thanks for your reply @sushilbpositive there is no issues. What my code is doing is first it is it is getting the selected records ID from the list view and when i click on download button on listview it is returning the PDF's for the records and it is saving to the notes and attachments and then it is downloading. So here, I dont want to save to notes and attachments I just want to download without saving anywhere. How can I do this?
ok.I just gone through your code, I think it should be possible. You can use the same BLOB to generate the JSON which you use to generate the Attachment. Bascially take body at line 41 and use that in line 107. You will have to move your JSON code up where you are geneating pdf from page. Have you tried that?