Salesforce Apex实现双PDF合并并关联自定义对象及邮件发送技术问询
How to Merge Two PDFs, Attach to a Custom Object, and Send via Email in Salesforce Apex
Hey there, let's walk through a proper solution for your requirement. First up, the approach you initially tried—just concatenating the hex strings of the two PDFs—won't work because PDFs have a specific file structure. Merging them that way will create a corrupted file that can't be opened. Instead, we'll use Salesforce's built-in PDFMerger class (available in API version 48.0 and later) to combine the PDFs correctly.
Here's the complete, working Apex code with explanations:
public static void mergePdfAndSend(Id customObjectRecordId) { // Step 1: Generate PDF blobs from your Visualforce pages PageReference firstPdfPage = new PageReference('/apex/FirstPDF?id=' + customObjectRecordId); Blob firstPdfBlob = firstPdfPage.getContentAsPDF(); // Prefer getContentAsPDF for reliable PDF output PageReference secondPdfPage = new PageReference('/apex/SecondPDF?id=' + customObjectRecordId); Blob secondPdfBlob = secondPdfPage.getContentAsPDF(); // Step 2: Merge the PDFs properly with PDFMerger PDFMerger pdfMerger = new PDFMerger(); pdfMerger.addDocument(firstPdfBlob); pdfMerger.addDocument(secondPdfBlob); Blob mergedPdf = pdfMerger.merge(); // Step 3: Create and attach the merged PDF to your custom object Attachment pdfAttachment = new Attachment(); pdfAttachment.Body = mergedPdf; pdfAttachment.Name = 'Combined_Document_' + DateTime.now().format('yyyyMMddHHmm') + '.pdf'; // Unique name to avoid conflicts pdfAttachment.ParentId = customObjectRecordId; // Link to your custom object record pdfAttachment.ContentType = 'application/pdf'; // Critical for correct file recognition try { insert pdfAttachment; System.debug('Merged PDF attached successfully: ' + pdfAttachment.Id); } catch(DmlException e) { System.debug('Error attaching PDF: ' + e.getMessage()); throw new AuraHandledException('Failed to save merged PDF: ' + e.getMessage()); } // Step 4: Send the merged PDF via email Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); email.setToAddresses(new String[] {'recipient@example.com'}); // Replace with actual recipient email(s) email.setSubject('Your Combined PDF Document'); email.setPlainTextBody('Hi there,\n\nPlease find your merged PDF document attached.\n\nThanks,\nYour Team'); // Prepare the email attachment Messaging.EmailFileAttachment emailAttachment = new Messaging.EmailFileAttachment(); emailAttachment.setFileName(pdfAttachment.Name); emailAttachment.setBody(mergedPdf); emailAttachment.setContentType('application/pdf'); email.setFileAttachments(new Messaging.EmailFileAttachment[] {emailAttachment}); try { Messaging.SendEmailResult[] results = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email}); if(results[0].isSuccess()) { System.debug('Email sent successfully'); } else { String errorMsg = results[0].getErrors()[0].getMessage(); System.debug('Failed to send email: ' + errorMsg); throw new AuraHandledException('Error sending email: ' + errorMsg); } } catch(Exception e) { System.debug('Unexpected error sending email: ' + e.getMessage()); throw new AuraHandledException('Failed to send email: ' + e.getMessage()); } }
Key Notes & Best Practices:
- PDF Generation: Use
getContentAsPDF()instead ofgetContent()to ensure you get a valid PDF blob—getContent()might return HTML if your Visualforce page has rendering issues. Also, make sure your VF pages include<apex:page renderAs="pdf">at the top to enforce PDF rendering. - Proper Merging: The
PDFMergerclass handles the underlying PDF structure, so your merged file will be fully functional. If you're stuck on an older API version withoutPDFMerger, you'd need to use a third-party PDF parsing library, butPDFMergeris the supported, recommended approach now. - Attachment Naming: Adding a timestamp to the attachment name helps avoid overwriting existing files if you run this process multiple times for the same record.
- Permissions: Ensure the user executing this Apex has access to both Visualforce pages, the custom object, and has the "Send Email" permission in their profile.
- Email Limits: Keep Salesforce's daily email limits in mind if you're running this for multiple records.
内容的提问来源于stack exchange,提问作者Veerpal
相关产品推荐
相关产品推荐

