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
fredkafredka 

Create PDF displaying null page

I have taken an example to create a PDF from an LWC.  From an LWC component I am calling an Aura enabled class.  That class passes the HTML using a variable to a visualforce page that renders as a PDF.

In my own development org, I am getting the expected results.  However, when I use the exact same code in another sandbox, I am getting a null PDF.  I put a debug in the controller for the visualforce page.  The debug does not post in the code that is not working. Therefore, it seems that my pagereference is not working.

As I mentioned, the exact code is working in my development org, just not in the sandbox that I copy it to.  Any suggestions on why that woudl happen?  thanks!!!
SwethaSwetha (Salesforce Developers) 
HI fredka,
Check if have any hardcoded URLs/custom settings/custom labels in your code that might be causing the issue.

If this not the case, can you share the code I can use to reproduce in my org. 

If this information helps, please mark the answer as best. Thank you
fredkafredka
Thanks for responding Swetha!  There is only one hardcode url in the javascript to open the attachment once it is created.  But that does not seem to be the issue.  This code is from a udemy course so I don't think there are any issues with the code.  I think something in my org is preventing this from working.  Prior to this I was trying to implement jspdf and also had issues.  That being said, here is the code I'm using.  

LWC HTML:
<template>
    <div class="container" style="background: white;
    padding: 16px;">
        <div style="margin-bottom: 50px;">
         <!--   <img src={imageUrl} style="height:40px; width:150px"/>  -->
            <div style="display: inline-block;float: right;">
                <div>Invoice #: {invoiceData.invoiceNo}</div>
                <div>Created #: {invoiceData.invoiceCreated}</div>
                <div>Due #: {invoiceData.invoiceDue}</div>
            </div>
        </div>
        <div>
            <div style="display: inline-block;">
                <div> {invoiceData.companyName}</div>
                <div> {invoiceData.address1}</div>
                <div> {invoiceData.address2}</div>
            </div>
            <div style="display: inline-block;float: right; text-align: right;">
                <div> {clientData.client}</div>
                <div> {clientData.username}</div>
                <div> {clientData.email}</div>
            </div>
        </div>
        <div style="background: #eee;
        margin: 16px 0px;
        padding: 8px;">
            <div  style="display: inline-block"><strong>Services</strong></div>
            <div style="display: inline-block;float: right;"><strong>Amount</strong></div>
        </div>
        <template iterator:service={services}>
            <div key={service.value.name} style="padding: 8px;">
                <div style="display: inline-block">{service.value.name}</div>
                <div style="display: inline-block;float: right;">${service.value.amount}</div>
            </div>
            <div if:true={service.last} key={service.value.name}  style="padding: 8px;">
                <div style="display: inline-block;float: right;"><strong>Total Amount:${totalAmount} </strong></div>
            </div>
        </template>
    </div>

    <lightning-button variant="brand" label="generate pdf" onclick={pdfHandler}></lightning-button>
</template>

LWC JS:
mport { LightningElement, api } from 'lwc';
import generatePDF from '@salesforce/apex/pdfController.generatePDF'
export default class PdfGenerationDemo extends LightningElement {
    @api recordId
   // imageUrl = 'https://www.sparksuite.com/images/logo.png'
    invoiceData={
        invoiceNo:'123',
        invoiceCreated:'January 1, 2019',
        invoiceDue:'January 10, 2020',
        companyName:'Sparksuite, Inc.',
        address1:'12345 Sunny Road',
        address2:' Sunnyville, CA 12345'
    }
    clientData={
        client:'Acme Corp',
        username:'John Doe',
        email:'john@example.com'
    }
    services=[
        {name:'Consultant fee', amount:1000.00},
        {name:'Website design', amount:300.00},
        {name:'Hosting (3 months)', amount:75.00}
    ]

    get totalAmount(){
        return this.services.reduce((total, service)=>{
            return total = total+service.amount
        }, 0)
    }

    pdfHandler(){
        let content = this.template.querySelector('.container')
        console.log(content.outerHTML)
        generatePDF({ recordId:this.recordId, htmlData:content.outerHTML}).then(result=>{
            console.log("attachment id", result)
            window.open(`https://horizonblue--lightning--c.cs21.content.force.com/servlet/servlet.FileDownload?file=${result.Id}`)
        }).catch(error=>{
            console.error(error)
        })
    }

  
}

Apex class called from Javascript:
 
public with sharing class pdfController {

    @AuraEnabled
   public static Attachment generatePDF(Id recordId, String htmlData){
        Pagereference page = Page.renderAsPDF;
        page.getParameters().put('pdfText', htmlData);

        Contact con = new Contact(Id=recordId);
        Attachment objAttachment = new Attachment();
        objAttachment.Name='invoice.pdf';
        objAttachment.ParentId = con.Id;
        objAttachment.Body = page.getContentaspdf();
        objAttachment.IsPrivate = false;
        insert objAttachment;
        return objAttachment;
    }
Visualforce Page used to display and create PDF:
<apex:page controller="pdfPageController" renderAs="pdf" applyHtmlTag="false" showHeader="false" cache="true" readOnly="true">
    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/> 
        </head>
        <body>
        <   apex:outputText value="{!pdfText}" escape="false"/>
        </body>
    </html>
</apex:page>

Visualforce Page Controller:
public with sharing class pdfPageController {
    public String pdfText{get;set;}

    public pdfPageController() {
        pdfText = String.escapeSingleQuotes(
            ApexPages.currentPage().getParameters().get('pdfText')
        );
        system.debug(LoggingLevel.INFO, '!!!!@@@@ IM IN ');
    }
}


​​​​​​
fredkafredka
I'm realizing that my visualforce page also is not generating a pdf when I use it in lightning.  THis is  a page that I have used in classic.  If I try to use it in classic, the PDF is generated,  however, if I try to use that same visualforce page in lightning, the second visualforce page that is used to renderAsPdf is never triggered.  So this seems to be an issue in my org for lightning.
Piyush VaddoriaPiyush Vaddoria
put "oauth_token" as a param to the page reference.
page.getParameters().put('oauth_token', userinfo.getSessionId());

This should work.