pdf-create-lowlevel.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Create a PDF from scratch.
  2. // This example creates a new PDF file from scratch, using only the low level APIs.
  3. // This assumes a basic working knowledge of the PDF file format.
  4. // Create a new empty document with no pages.
  5. var pdf = new PDFDocument()
  6. // Create and add a font resource.
  7. var font = pdf.addObject({
  8. Type: "Font",
  9. Subtype: "Type1",
  10. Encoding: "WinAnsiEncoding",
  11. BaseFont: "Times-Roman",
  12. })
  13. // Create and add an image resource:
  14. var image = pdf.addRawStream(
  15. // The raw stream contents, hex encoded to match the Filter entry:
  16. "004488CCEEBB7733>",
  17. // The image object dictionary:
  18. {
  19. Type: "XObject",
  20. Subtype: "Image",
  21. Width: 4,
  22. Height: 2,
  23. BitsPerComponent: 8,
  24. ColorSpace: "DeviceGray",
  25. Filter: "ASCIIHexDecode",
  26. }
  27. );
  28. // Create resource dictionary.
  29. var resources = pdf.addObject({
  30. Font: { Tm: font },
  31. XObject: { Im0: image },
  32. })
  33. // Create content stream.
  34. var buffer = new Buffer()
  35. buffer.writeLine("10 10 280 330 re s")
  36. buffer.writeLine("q 200 0 0 200 50 100 cm /Im0 Do Q")
  37. buffer.writeLine("BT /Tm 16 Tf 50 50 TD (Hello, world!) Tj ET")
  38. var contents = pdf.addStream(buffer)
  39. // Create page object.
  40. var page = pdf.addObject({
  41. Type: "Page",
  42. MediaBox: [0,0,300,350],
  43. Contents: contents,
  44. Resources: resources,
  45. })
  46. // Insert page object into page tree.
  47. var pagetree = pdf.getTrailer().Root.Pages
  48. pagetree.Count = 1
  49. pagetree.Kids = [ page ]
  50. page.Parent = pagetree
  51. // Save the document.
  52. pdf.save("out.pdf")