Skip to content

Instantly share code, notes, and snippets.

@peterpeterparker
Created November 7, 2020 13:47
Show Gist options
  • Save peterpeterparker/c3fddfe81d5d19eca2ec102fe2821d45 to your computer and use it in GitHub Desktop.
Save peterpeterparker/c3fddfe81d5d19eca2ec102fe2821d45 to your computer and use it in GitHub Desktop.
Create a PDF manually with JavaScript
const fs = require('fs');
/**
* Source: Mario's Security Blog - http://mariomalwareanalysis.blogspot.com/2012/02/how-to-manually-create-pdf.html
*/
function generatePDF() {
const lines = [];
lines.push(`%PDF-1.3`);
lines.push(`%\xFF\xFF\xFF\xFF`);
lines.push(``);
lines.push(`1 0 obj`);
lines.push(`<<`);
lines.push(`/Type /Catalog`);
lines.push(`%/OpenAction`);
lines.push(`/Pages 2 0 R`);
lines.push(`>>`);
lines.push(`endobj`);
lines.push(``);
lines.push(`2 0 obj`);
lines.push(`<<`);
lines.push(`/Type /Pages`);
lines.push(`/Count 1`);
lines.push(`/Kids [3 0 R]`);
lines.push(`>>`);
lines.push(`endobj`);
lines.push(``);
lines.push(`3 0 obj`);
lines.push(`<<`);
lines.push(`/Type /Page`);
lines.push(`/Parent 2 0 R`);
lines.push(`/Resources << /Font << /F1 5 0 R >>`);
lines.push(`>>`);
lines.push(`/MediaBox [0 0 612 792]`);
lines.push(`/Contents 4 0 R`);
lines.push(`>>`);
lines.push(`endobj`);
lines.push(``);
lines.push(`4 0 obj`);
lines.push(`<< /Length 45 >>`);
lines.push(`stream`);
lines.push(`BT`);
lines.push(`/F1 24 Tf`);
lines.push(`250 700 Td (Hello, World!) Tj`);
lines.push(`ET`);
lines.push(`endstream`);
lines.push(`endobj`);
lines.push(``);
lines.push(`5 0 obj`);
lines.push(`<<`);
lines.push(`/Type /Font`);
lines.push(`/Subtype /Type1`);
lines.push(`/BaseFont /Helvetica`);
lines.push(`>>`);
lines.push(`endobj`);
lines.push(``);
lines.push(`xref`);
lines.push(`0 6`);
lines.push(`trailer`);
lines.push(`<<`);
lines.push(`/Size 6`);
lines.push(`/Root 1 0 R`);
lines.push(`>>`);
lines.push(`startxref`);
lines.push(`%%EOF`);
fs.writeFileSync('./test.pdf', lines.join('\n'));
}
generatePDF();
@peterpeterparker
Copy link
Author

A screenshot of the output of the above function.

Capture d’écran 2020-11-07 à 14 57 46

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment