[SalesForce] How to generate a PDF for an SObject without using Visualforce

How do I print the selected records fields and values as PDF on the flow of Apex. I don't want to create seperate visualforce page and getContentAsPDF().

Am on the Custom object record and i want to pass this current record to the page reference. How can i achieve this?

blob body;
PageReference pdf = new PageReference('current record url' + id)
body = pdf.getContentAsPDF();

Above code is working for seperate visualforce page. But i don't have visualforce page so want to pass my custom object record id. How to do that?

Thanks in Advance

Best Answer

Unfortunately, I think you are out of luck for this. When the standard Salesforce layout is used for a Record (or even the Printer friendly version) it is served from a different domain to Visualforce (thanks to @mattandneil for this one) which then causes problems in the PDF generation.

For example, the following Apex causes an Internal Salesforce Error in my org and reports "PDF generation failed. Check the page markup is valid."

PageReference pdf = new PageReference('/a1158000000POgn/p?retURL=/a1158000000POgn');
String content = pdf.getContentAsPDF();

Checkout this question/answer, ignore the bits about BatchPDF as it's not relevant to your case, but the accepted answer has some clever Apex to strip out unnecessary tags etc. and return only valid HTML that can be displayed in a PDF (this still requires a Visualforce page/Controller - but it is very simple).

You might want to review this document which gives some general tips on creating PDFs.

The other thing you might consider is actually building the PDF in your Apex as described in this blog post. Again, this might be more effort than using a Visualforce page (be careful of unsupported tags).