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
Mustafa JhabuawalaMustafa Jhabuawala 

Inserting a PDF in attachments object

What I wanted to do is I storing a PDF into attachments object through apex

Here is the apex code -
Blob body = Blob.valueOf('Some Text');
Attachment attach = new Attachment();
attach.Body = body;
attach.Name = 'Sample.pdf'; 
attach.IsPrivate = false;
attach.ParentId = '00641000004n7fEAAQ';
insert attach;

Now when I navigate to the object on which I have linked this attachment, click on the file it doesn't get loaded. Following error is displayed

User-added image

There is something wrong while inserting the record.

Can somebody help me.

Note - I need pdf file to be attached to the object

 
Best Answer chosen by Mustafa Jhabuawala
yogesh_sharmayogesh_sharma

Hello Mustafa,

You are trying to save this attachment in PDF format then you have to convert your string in blob.toPDF format.

Try this Code:

Blob body = Blob.toPDF('Some Text');
Attachment attach = new Attachment();
attach.Body = body;
attach.Name = 'Sample.pdf';
attach.IsPrivate = false;
attach.ParentId = '00641000004n7fEAAQ';
insert attach;


I hope this helps you. Mark this Answer as best Answer, if it helpful.

Thanks,

Yogesh Sharma