Print & download option comes from the browser's pdf viewer.
If you still want to have a button somewhere in your org to download the page, have the button, onclick of which redirect the user to the VF page and when the page load, have the following line in the constructor of the controller
Apexpages.currentPage().getHeaders().put('content-disposition', 'attachment; filename=YourFileName.pdf');
It should save a PDF in your local drive.
You can have a salesforce button for print as well.
window.print()
is the function you need to call from the button, it will send the current page for print.
Please note: you can not have this Javascript in a VF page which is rendered as PDF, JS doesn't run when the page is rendered as PDF.
When you return the body using HttpResponse.getBody()
, it's going to be converted to a string like Blob[12345]
. This won't be interpreted correctly as a PDF. You need to encode it as Base-64 first:
return EncodingUtil.base64Encode(rsp.getBodyAsBlob());
The page itself was being interpreted as PDF because of contentType="application/pdf"
. This caused the browser to try to interpret the HTML script as PDF, which caused the errors.
Fixing your VF code, and controller, results in the following:
public class pdfDownloadController {
public String getPdf() {
HttpRequest req = new HttpRequest();
req.setEndpoint('https://www.irs.gov/pub/irs-pdf/fw4.pdf');
req.setMethod('GET');
// Make call
Http client = new Http();
HttpResponse rsp = client.send(req);
return EncodingUtil.base64Encode(rsp.getBodyAsBlob());
}
}
<apex:page controller="pdfDownloadController" sidebar="false" showHeader="false">
<script>
window.location.href = "data:application/pdf;base64,{!pdf}";
</script>
</apex:page>
This however, results in a new error:
Not allowed to navigate top frame to data URL: ...
It appears that this method is now blocked by web browsers.
So, basically, the method you're looking for is not directly available.
However, with a bit of HTML magic:
<apex:page controller="pdfDownloadController" sidebar="false" showHeader="false">
<embed type="application/pdf" src="data:application/pdf;base64,{!pdf}" style="width: 100%; height: 100vh; display: inline-block" />
</apex:page>
We're able to display the PDF in the page. If you want something else, you might need to save the file as a ContentDocument if you want to be able to download/save/etc the file.
Best Answer
Simply use
Window.Print()
function and add that function to a button click event.