+ Start a Discussion
WizradWizrad 

PDF Attachments & Base 64 Decoding

Noticing some oddities with base 64 decoding PDF attachments.

 

(1) Create a visualforce page that renders as PDF.  Save the resulting PDF as an attachment to salesforce.  Lets call the resulting PDF "original pdf".

(2) Write some javascript

 

var results = sforce.connection.query("SELECT Name, Body FROM Attachment WHERE Id ='<id of attachment i just uploaded>' ");
var records = results.getArray("records");
var unencodedPDF = sforce.Base64Binary.prototype.decode(records[0].Body);

 (3) Turn unencodedPDF into a pdf.  Lets call this "new pdf".

 (4) Compare "original pdf" and "new pdf".  Notice "new pdf" is just a blank white page.

 

What am I missing?

Best Answer chosen by Admin (Salesforce Developers) 
WizradWizrad

Ultimately I am delivering these PDFs via JSZip, and found it is better to not bother trying to decode them, and instead tell JSZip that the files I am adding to the zip are base64.

All Answers

WizradWizrad

I've broken this down into a simple example.  Take the following two visualforce pages.

 

SimplePDF.page

 

<apex:page showHeader="false" standardStylesheets="false" sidebar="false" renderAs="pdf">
hello world
</apex:page>

 

SimplePDFTest.page

 

<apex:page showHeader="false" standardStylesheets="false" sidebar="false">
	<head>
		<apex:includeScript value="../../soap/ajax/21.0/connection.js" />
		<script>
			sforce.connection.sessionId = '{!$Api.Session_ID}';
			var results = sforce.connection.query("SELECT Name, Body FROM Attachment WHERE Id = '<id of SimplePDF.page as attachment>'");
			var records = results.getArray("records");
			var unencodedPDF = sforce.Base64Binary.prototype.decode(records[0].Body);
			console.log(unencodedPDF);
		</script>
	</head>
	<body>
	</body>
</apex:page>

 

Take the value in your javascript console that resulted from the console.log statement.  Copy it.  Paste it into your plain text editor of choice.  Save as "SimplePDF.pdf".  Open the pdf.  Note it is entirely blank.

 

I am thinking maybe...

 

sforce.Base64Binary.prototype.decode() 

 ...may not be suitable for decoding PDFs as it returns a string and not a binary array.

 

Anyone have any ideas?

 

WizradWizrad

Ultimately I am delivering these PDFs via JSZip, and found it is better to not bother trying to decode them, and instead tell JSZip that the files I am adding to the zip are base64.

This was selected as the best answer