I’m stuck trying to get a PDF from a website using the Code step in Zapier. My JavaScript isn’t working right. The file I get is just a mess of weird characters. Maybe I need to encode it somehow? Here’s what I’ve got so far:
Can anyone help me fix this? Also, what if the PDF is on a site that needs a username and password? How would I change the code for that? Thanks for any tips!
Your approach is on the right track, but you’re missing a crucial step. When fetching binary data like PDFs, you need to specify the response type as ‘arraybuffer’ in the fetch options. Here’s an improved version:
For sites requiring authentication, you’d need to include credentials in the fetch options. Be cautious with storing sensitive information in your Zaps. Consider using Zapier’s built-in auth methods or environment variables for credentials when possible.
I’ve dealt with similar PDF issues in Zapier before. One thing to watch out for is the Content-Type header in the response. Sometimes servers don’t set it correctly for PDFs. You might want to add a check:
function getPDF() {
const url = 'https://example.com/sample.pdf';
return fetch(url, { method: 'GET' })
.then(response => {
if (!response.headers.get('Content-Type').includes('application/pdf')) {
throw new Error('Not a PDF');
}
return response.arrayBuffer();
})
.then(data => {
const result = {fileId: 'doc001', content: Buffer.from(data).toString('base64')};
return result;
})
.catch(error => console.error('Error:', error));
}
For auth, I’d recommend using Zapier’s built-in HTTP auth if possible. It’s more secure than hardcoding credentials. If you must use basic auth in the code, never store passwords directly in your Zap. Use environment variables instead.