How to create a Visualforce Page to Generate PDF Invoices and Attach to Related Records

VF Page Code:

Visualforce Page (TaxInvoicePage): This Visualforce page is designed to display invoice details and provide functionality to attach the invoice as a PDF to the related record’s Files section.

  • Standard Controller (Invoice__c): The page is associated with the standard controller for the Invoice__c object, allowing it to access and display invoice details.
  • Extensions (ItemSubmissionInvoiceController): The page is extended by a custom controller ItemSubmissionInvoiceController. This controller handles the logic for generating the PDF and attaching it to the related record.
  • Page Title: The page title is dynamic, showing the invoice name along with the individual or company name based on certain conditions.
  • Google Fonts: The page includes a link to Google Fonts for styling purposes.
  • Navigation and Printing Buttons: There are buttons for navigation, printing, and attaching the PDF. JavaScript functions go_back() and print_page() are defined to handle these actions.

 

VF Page Code

<apex:page standardController=”Invoice__c” extensions=”ItemSubmissionInvoiceController” title=”{!Invoice__c.Name} / {!IF(Invoice__c.Account__r.Individual__c, Invoice__c.Account__r.Individual_First_Name__c +’ ‘+ Invoice__c.Account__r.Individual_Last_Name__c, Invoice__c.Account__r.CR_Official_Name__c)}”>

<apex:form >

<!– Google Font Section –>

<head>

<link rel=”preconnect” href=”https://fonts.gstatic.com” />

<link href=”https://fonts.googleapis.com/css2?family=Arsenal:wght@400;700&display=swap” rel=”stylesheet” />

</head>

 

<!– Navigation and Printing Buttons –>

<div style=”text-align:center;”>

<br />

<script type=”text/javascript”>

function go_back() {

window.history.back();

}

 

function print_page() {

var backButton = document.getElementById(“back”);

var printButton = document.getElementById(“btnprint”);

var header = document.getElementById(“header”);

var footer = document.getElementById(“footer”);

 

// Hide the back button and header

backButton.style.visibility = “hidden”;

header.style.display = “block”;

footer.style.display = “block”;

 

// Print the page

printButton.style.visibility = “hidden”;

window.print();

 

// Show the back button and header again

backButton.style.visibility = “visible”;

header.style.display = “none”;

footer.style.display = “none”;

printButton.style.visibility = “visible”;

// Function to remove currency symbol “BHD” from the value

/*function removeCurrency(value) {

if (value != null) {

return value.replace(‘BHD’, ”);

} else {

return ”;

}

}*/

}

</script>

 

<apex:commandButton value=”Attach PDF” action=”{!attachPDF}” />

<input type=”button” id=”back” value=”Back” onclick=”go_back()” />

<input type=”button” id=”btnprint” value=”Print” onclick=”print_page(), go_back()” />

</div>

VF Page code here….

</apex:page>

 

Controller Class:

Controller Class (ItemSubmissionInvoiceController): This Apex controller handles the backend logic for generating the PDF and attaching it to the related record.

  • Variables:
    • inv: Stores the current Invoice__c record.
    • submissions: Holds a list of related Item_Submission__c records for the invoice.
    • stdController: Reference to the standard controller.
  • Constructor (ItemSubmissionInvoiceController):
    • Initializes the controller with the standard controller and retrieves the current invoice record (inv).
    • Queries related Item_Submission__c records associated with the invoice.
  • Method attachPDF():
    • Generates a PDF blob from the Visualforce page (TaxInvoicePage).
    • Creates a ContentVersion object to store the PDF file as a Salesforce File (ContentVersion).
    • Sets the title of the PDF dynamically based on the invoice name and current date/time.
    • Inserts the ContentVersion into Salesforce Files related to the invoice.
    • Redirects to the invoice record page after attachment.

 

Controller Class with Method

 

public with sharing class ItemSubmissionInvoiceController {

public Invoice__c inv { get; private set; }

public List<Item_Submission__c> submissions { get; set; }

private ApexPages.StandardController stdController;

 

public ItemSubmissionInvoiceController(ApexPages.StandardController stdController) {

this.stdController = stdController;

 

// Get the current “Invoice” record

inv = (Invoice__c) stdController.getRecord();

 

// Query related “Item_Submission__c” records

submissions = [SELECT Name, Take_in_number__c, Report_Type__c, Submitted_Date__c, Product__c, Vat_Amount__c, Total__c, Item_Total__c, Pieces__c, Weight__c,

Units__c, Submission_ID_Backend__c, Description__c, Pro_Strung_Length__c, Pearl_Strung_Rows__c, Pearl_Strung_Detail_List__c, Average_Diameter__c,

Quantity__c, Discount__c, Discount_Amount__c, Duplicate_Report_Price__c, Duplicate_Report_Vat_Amount__c, Duplicate_Report_Price_Item_Total__c,

Remarks__c, Item_Type__c, Items__c

FROM Item_Submission__c WHERE Invoice__c = :inv.Id];

}

 

 public PageReference attachPDF() {

        // Generate PDF content from the Visualforce page

        Blob pdfBlob = Page.TaxInvoicePage.getContentAsPDF();

    

        // Create ContentVersion object to store the PDF file as a Salesforce File

        ContentVersion cv = new ContentVersion();

        String currentDate = Datetime.now().formatGMT(‘yyyy-MM-dd_HH:mm’);

        cv.Title = inv.Name + ‘_’ + currentDate + ‘.pdf’; // Set the PDF title dynamically with date and time

        cv.PathOnClient = cv.Title; // File name on the client side

        cv.VersionData = pdfBlob;

        cv.FirstPublishLocationId = inv.Id; // ParentId (Invoice__c record Id)

        cv.ContentLocation = ‘S’; // ‘S’ indicates Salesforce Files

        insert cv;

    

        // Redirect to the Invoice__c record page

        PageReference invoicePage = new PageReference(‘/’ + inv.Id);

        invoicePage.setRedirect(true); // Ensure a redirect after attachment

        return invoicePage;

    }

}

 

The implementation described in the post demonstrates an efficient method for generating PDF invoices within the Salesforce environment. By leveraging Visualforce pages and Apex controllers, the system provides dynamic functionality for displaying invoice details, attaching generated PDFs to related records, and enabling user interactions such as navigation and printing.

preloader image