2

I am generating a PDF from a trigger, the problem comes when displaying the styles. It does not work in any way, I have tried: enter image description here

And: enter image description here

But the styles in the pdf do not apply: enter image description here

An example of the code I am working with:

String htmlBody = '<html><head><style type="text/css">table{border: 1px solid black;}</style></head><body><table><tr><th>HI</th></tr></table></body></html>';
Blob bodyData;
try {
    bodyData = Blob.toPDF(htmlBody);
} catch (Exception e) {
}
Attachment attachmentPDF = new Attachment();
attachmentPDF.parentId = 'ID OF RELATED RECORD';
attachmentPDF.Name = 'Attach.pdf';
attachmentPDF.body = bodyData;
attachmentPDF.ContentType = 'pdf';

insert attachmentPDF;
2
  • 1
    There is try/catch exception swallowing any error, and that is usually a bad practice. So, have you checked if there is no exceptions being thrown? Jul 13, 2021 at 9:30
  • It is a simplified code for testing. In my sandbox there is an error log where if there is any exception it is saved in the system.
    – Alex M.
    Jul 13, 2021 at 12:15

1 Answer 1

0

For my case it's works with:

handlerTrigger.cls

    @future(callout=true)
    public static void method(String recordId){
        Attachment attachmentPDF;
        Blob body;
        PageReference pdf;
    
        pdf = Page.VISUALFORCE;

        pdf.setRedirect(true);
        pdf.getParameters().put('id', recordId);
        body = pdf.getContentAsPDF();
            
        attachmentPDF = new Attachment();
        attachmentPDF.parentId = recordId;
        attachmentPDF.Name = 'file.pdf';
        attachmentPDF.Body = body;
        attachmentPDF.ContentType = 'pdf';

        insert attachmentPDF;
    }

VISUALFORCE

<apex:page standardController="Case" showHeader="false" extensions="controller">
<table style="border-collapse: collapse;border: 1px solid black;">
<apex:repeat value="{!cases}" var="case">
<tr>
    <td style="border: 1px solid black;">
        <apex:outputText value="{!case.CaseNumber}"/>
    </td>
</tr>
</apex:repeat>
</table>

Controller

public class controller{

    private static Case case1 = [SELECT CaseNumber FROM Case WHERE Id =:ApexPages.currentPage().getParameters().get('id')];

    public static Case getCases(){
       return case1;
    }
}
3
  • This is not without a visualforce though. Also if you need a single record, standard controller is enough and extension is not required.
    – Raul
    Jul 12, 2021 at 12:33
  • Yah i know, but i ask for a solution without visualforce because you cant use visualforce in trigger unless you use @future(callout=true)
    – Alex M.
    Jul 13, 2021 at 9:13
  • I have changed the title to avoid confusion
    – Alex M.
    Jul 13, 2021 at 9:16

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .