### Start Writing a Dictionary Source: https://github.com/julianhille/muhammarajs/wiki/Extensibility Initiate the creation of a PDF dictionary. This method writes the dictionary starter code to the PDF file. ```javascript var dict = objCxt.startDictionary() ``` -------------------------------- ### Start Writing an Array Source: https://github.com/julianhille/muhammarajs/wiki/Extensibility Begin the creation of a PDF array using the object context. ```javascript objCxt.startArray() ``` -------------------------------- ### Basic Express Server Setup Source: https://github.com/julianhille/muhammarajs/wiki/How-to-serve-dynamically-created-pdf Sets up a basic Express server that listens on port 3000 and prepares to serve a PDF response. ```javascript var express = require('express'); var app = express(); app.get('/', function(req, res){ res.writeHead(200, {'Content-Type': 'application/pdf'}); /** here we will place the pdf building code **/ res.end(); }); app.listen(3000); ``` -------------------------------- ### Install Header Files for LibAesgm Source: https://github.com/julianhille/muhammarajs/blob/develop/src/deps/LibAesgm/CMakeLists.txt Installs the header files for the LibAesgm library. It copies all .h files from the current source directory to the include directory. ```cmake install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} DESTINATION include COMPONENT dependencies FILES_MATCHING PATTERN "*.h" ) ``` -------------------------------- ### Start Writing a PDF Stream with a Predefined Dictionary Source: https://github.com/julianhille/muhammarajs/blob/develop/docs/Extensibility.md Starts writing a PDF stream, providing a custom dictionary for the stream's header. The library will automatically add required keys like 'Length' and the encoder. ```javascript objCxt.startPDFStream(dictionary) ``` -------------------------------- ### Start Writing a PDF Stream Source: https://github.com/julianhille/muhammarajs/wiki/Extensibility Initiate the creation of a PDF stream. This method returns a PDF stream object for writing data. ```javascript var streamCxt = objCxt.startPDFStream() ``` -------------------------------- ### Install MuhammaraJS Source: https://github.com/julianhille/muhammarajs/blob/develop/README.md Install the MuhammaraJS package using npm. Note specific configurations for pnpm users to enable lifecycle scripts. ```bash npm install muhammara ``` -------------------------------- ### Creating and Using a Content Context Source: https://github.com/julianhille/muhammarajs/wiki/Use-the-pdf-drawing-operators Demonstrates how to start a content context for a page and use operators within it, including saving and restoring the graphic state. ```APIDOC ## POST /api/pages/content ### Description Allows direct manipulation of PDF page content by providing access to PDF operators through a content context. ### Method POST ### Endpoint /api/pages/content ### Parameters #### Request Body - **page** (object) - Required - The page object to which content will be added. - **operations** (array) - Required - An array of operations to perform on the content context. ### Request Example ```json { "page": "page_object", "operations": [ { "operator": "q" }, { "operator": "cm", "params": [2, 0, 0, 2, 0, 0] }, { "operator": "Q" } ] } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. #### Response Example ```json { "status": "Content added successfully" } ``` ``` -------------------------------- ### Start Writing a PDF Stream with Dictionary Source: https://github.com/julianhille/muhammarajs/wiki/Extensibility Begin writing a PDF stream, providing a pre-defined dictionary for its properties. The dictionary will be closed automatically. ```javascript startPDFStream(dictionary) ``` -------------------------------- ### Create PDF Content Context Source: https://github.com/julianhille/muhammarajs/wiki/Show-primitives Initialize a content context for a given page to start drawing elements. This is the first step before drawing any primitives. ```javascript var cxt = pdfWriter.startPageContentContext(page); ``` -------------------------------- ### Install LibAesgm Target Source: https://github.com/julianhille/muhammarajs/blob/develop/src/deps/LibAesgm/CMakeLists.txt Installs the LibAesgm target, including runtime, archive, and library destinations. It also assigns the target to the PDFHummusTargets export set. ```cmake install(TARGETS LibAesgm EXPORT PDFHummusTargets RUNTIME DESTINATION bin COMPONENT dependencies ARCHIVE DESTINATION lib${LIB_SUFFIX} COMPONENT dependencies LIBRARY DESTINATION lib${LIB_SUFFIX} COMPONENT dependencies ) ``` -------------------------------- ### Initialize PDF Writer Source: https://github.com/julianhille/muhammarajs/wiki/Basic-pdf-creation Use `createWriter` to start a new PDF file or stream. It returns a PDFWriter object for further operations. Options can be provided for PDF version and compression. ```javascript createWriter(inFileName,[inOptions]); ``` ```javascript createWriter(inStreamObject,[inOptions]); ``` -------------------------------- ### Start Writing an Unfiltered PDF Stream Source: https://github.com/julianhille/muhammarajs/wiki/Extensibility Initiate the creation of a PDF stream without automatic filtering (e.g., flate compression). ```javascript startUnfilteredPDFStream() ``` -------------------------------- ### Direct Stream Writing with Free Context Source: https://github.com/julianhille/muhammarajs/wiki/Extensibility Use `startFreeContext` to get a `ByteWriterWithPosition` stream for direct writing. Call `endFreeContext` to return control to hummus. ```javascript var writeStream = objCxt.startFreeContext() // Use writeStream.write(inBytesArray) and writeStream.getCurrentPosition() objCxt.endFreeContext() ``` -------------------------------- ### Parse and Read PDF Information with MuhammaraJS Source: https://context7.com/julianhille/muhammarajs/llms.txt Use `createReader` to parse an existing PDF and extract information. This example shows how to get PDF version, page count, encryption status, and page details. ```javascript const muhammara = require('muhammara'); // Create reader for existing PDF const pdfReader = muhammara.createReader('./document.pdf'); // Get high-level information console.log('PDF Version:', pdfReader.getPDFLevel()); console.log('Page Count:', pdfReader.getPagesCount()); console.log('Is Encrypted:', pdfReader.isEncrypted()); // Get page information for (let i = 0; i < pdfReader.getPagesCount(); i++) { const pageInfo = pdfReader.parsePage(i); console.log(`Page ${i + 1}:`, { mediaBox: pageInfo.getMediaBox(), cropBox: pageInfo.getCropBox(), rotation: pageInfo.getRotate() }); } // Access PDF trailer and low-level objects const trailer = pdfReader.getTrailer(); const catalogRef = pdfReader.queryDictionaryObject(trailer, 'Root'); const catalog = catalogRef.toPDFDictionary(); console.log('Catalog:', catalog.toJSObject()); // Parse specific object by ID const obj = pdfReader.parseNewObject(5); if (obj.getType() === muhammara.ePDFObjectDictionary) { console.log('Object 5:', obj.toPDFDictionary().toJSObject()); } ``` -------------------------------- ### Initialize PDFPageModifier (Default) Source: https://github.com/julianhille/muhammarajs/wiki/Modification Use the default constructor to create a PDFPageModifier. Graphics added will reuse the global graphic state setup. ```javascript var pageModifier = new hummus.PDFPageModifier(pdfWriter,0); ``` -------------------------------- ### Create PDF Writer Source: https://github.com/julianhille/muhammarajs/blob/develop/docs/Basic-pdf-creation.md Use `createWriter` to start a PDF file or stream. It returns a PDFWriter object for further operations. Supports writing to a file path or a stream object. ```javascript createWriter(inFileName, [inOptions]); createWriter(inStreamObject, [inOptions]); ``` -------------------------------- ### Using PDFStreamForResponse for HTTP Output Source: https://github.com/julianhille/muhammarajs/blob/develop/docs/Custom-streams.md Example of creating a PDF writer that outputs directly to an HTTP response object. Ensure headers are set and the response is ended properly. ```javascript res.writeHead(200, { "Content-Type": "application/pdf" }); var pdfWriter = hummus.createWriter(new hummus.PDFStreamForResponse(res)); /** use pdfwriter to write pdf content **/ res.end(); ``` -------------------------------- ### Create a New PDF with MuhammaraJS Source: https://context7.com/julianhille/muhammarajs/llms.txt Use `createWriter` to generate a new PDF file. This example demonstrates creating a page, loading a font, writing text, and saving the PDF. ```javascript const muhammara = require('muhammara'); // Create PDF to file const pdfWriter = muhammara.createWriter('./output.pdf', { version: muhammara.ePDFVersion17, // PDF version 1.7 compress: true, // Enable compression (default) log: './debug.log' // Optional debug log file }); // Create a page (595x842 = A4 size in points) const page = pdfWriter.createPage(0, 0, 595, 842); // Get content context for drawing const ctx = pdfWriter.startPageContentContext(page); // Load a font and write text const font = pdfWriter.getFontForFile('./fonts/arial.ttf'); ctx.writeText('Hello, World!', 100, 700, { font: font, size: 24, colorspace: 'rgb', color: 0x000000 }); // Write the page and finish pdfWriter.writePage(page); pdfWriter.end(); ``` -------------------------------- ### Start and End Indirect Objects with Hummus Source: https://github.com/julianhille/muhammarajs/wiki/Extensibility Use these methods to begin and conclude writing indirect PDF objects. Indirect objects can be referenced from other parts of the PDF. ```javascript startNewIndirectObject([inObjectID]) endIndirectObject() allocateNewObjectID() ``` -------------------------------- ### Create and Write PDF Page Source: https://github.com/julianhille/muhammarajs/wiki/Basic-pdf-creation Use `createPage` on the PDFWriter object to start a new page, optionally defining its media box dimensions. Then, use `writePage` to add the content of the created page to the PDF. ```javascript pdfWriter.createPage(0,0,595,842) ``` ```javascript pdfWriter.writePage(aPage) ``` -------------------------------- ### Draw Shapes and Paths in PDF with Muhammara.js Source: https://context7.com/julianhille/muhammarajs/llms.txt Illustrates how to use the content context to draw basic shapes like rectangles and circles, as well as custom paths. Supports fill and stroke operations with various color spaces and line widths. Includes an example of low-level PDF operator usage. ```javascript const muhammara = require('muhammara'); const pdfWriter = muhammara.createWriter('./shapes.pdf'); const page = pdfWriter.createPage(0, 0, 595, 842); const ctx = pdfWriter.startPageContentContext(page); // Draw filled rectangle ctx.drawRectangle(50, 700, 100, 50, { type: 'fill', colorspace: 'rgb', color: 0x3366CC }); // Draw stroked circle ctx.drawCircle(200, 725, 30, { type: 'stroke', colorspace: 'rgb', color: 0xFF0000, width: 2 }); // Draw custom path ctx.drawPath(300, 700, 350, 750, 400, 700, 350, 650, 300, 700, { type: 'fill', colorspace: 'cmyk', color: 0xFF00FF00 // Magenta }); // Low-level PDF operators for complex graphics ctx.q() // Save graphics state .w(3) // Line width .RG(0, 0.5, 0) // Stroke color (RGB green) .m(50, 600) // Move to .l(150, 650) // Line to .l(100, 550) // Line to .h() // Close path .S() // Stroke .Q(); // Restore graphics state pdfWriter.writePage(page); pdfWriter.end(); ``` -------------------------------- ### Encrypt PDF with Passwords and Permissions using Muhammara.js Source: https://context7.com/julianhille/muhammarajs/llms.txt Demonstrates how to create a new PDF with user and owner passwords, and set specific user protection flags (e.g., print-only). Also shows how to re-encrypt an existing PDF using `recrypt` and how to open an encrypted PDF for reading with a password. ```javascript const muhammara = require('muhammara'); // Create encrypted PDF during creation const pdfWriter = muhammara.createWriter('./encrypted.pdf', { userPassword: 'viewpassword', ownerPassword: 'editpassword', userProtectionFlag: 4 // Print only permission }); const page = pdfWriter.createPage(0, 0, 595, 842); const ctx = pdfWriter.startPageContentContext(page); const font = pdfWriter.getFontForFile('./fonts/Helvetica.ttf'); ctx.writeText('This PDF is password protected', 100, 700, { font: font, size: 18, colorspace: 'rgb', color: 0x000000 }); pdfWriter.writePage(page); pdfWriter.end(); // Re-encrypt existing PDF with recrypt muhammara.recrypt('./unprotected.pdf', './protected.pdf', { userPassword: 'secret', ownerPassword: 'admin', userProtectionFlag: 4 // 4 = print allowed }); // Open encrypted PDF for reading const reader = muhammara.createReader('./encrypted.pdf', { password: 'viewpassword' }); console.log('Pages:', reader.getPagesCount()); ``` -------------------------------- ### Initialize MuhammaraJS Recipe Source: https://github.com/julianhille/muhammarajs/blob/develop/README.md Import the Recipe class from MuhammaraJS to begin creating or modifying PDF documents. ```javascript const Recipe = require('muhammara').Recipe ``` -------------------------------- ### Get Page Information Source: https://github.com/julianhille/muhammarajs/blob/develop/README.md Retrieves and logs information about a specific page in a PDF document. ```javascript const Recipe = require("muhammara").Recipe; const pdfDoc = new Recipe("input.pdf", "output.pdf"); console.log(pdfDoc.pageInfo(1)); ``` -------------------------------- ### Write PDF Comment in Hummus Source: https://github.com/julianhille/muhammarajs/blob/develop/docs/Extensibility.md Writes a string as a PDF comment, starting with '%'. A space is added after the comment. ```javascript writeComment(inComment); ``` -------------------------------- ### Set up Express Server for PDF Generation Source: https://github.com/julianhille/muhammarajs/blob/develop/docs/How-to-serve-dynamically-created-pdf.md This code sets up a basic Express server that listens on port 3000. It configures the response header to 'application/pdf' to ensure the client interprets the output correctly. ```javascript var express = require("express"); var app = express(); app.get("/", function (req, res) { res.writeHead(200, { "Content-Type": "application/pdf" }); /** here we will place the pdf building code **/ res.end(); }); app.listen(3000); ``` -------------------------------- ### Initialize Muhammara PDF Writer Source: https://github.com/julianhille/muhammarajs/blob/develop/docs/How-to-serve-dynamically-created-pdf.md Fetches the muhammara module and creates a PDF writer instance. It uses `PDFStreamForResponse` to write the PDF directly to the Express server's response object. ```javascript var muhammara = require("muhammara"); var pdfWriter = muhammara.createWriter(new muhammara.PDFStreamForResponse(res)); ``` -------------------------------- ### PDF Creation with createWriter Source: https://github.com/julianhille/muhammarajs/wiki/Basic-pdf-creation This section details how to initiate the PDF creation process using the `createWriter` method, which can target either a file path or a stream object. ```APIDOC ## Create PDFs The `hummus.createWriter` method is used for starting a PDF file or stream. ### Method Signature ```javascript createWriter(inFileName, [inOptions]); createWriter(inStreamObject, [inOptions]); ``` ### Parameters #### `inFileName` (string) - **Type**: string - **Description**: The UTF-8 encoded file path where the PDF will be saved. #### `inStreamObject` (object) - **Type**: object - **Description**: An object implementing `write` and `getCurrentPosition` methods. `Hummus.PDFStreamForResponse` is a provided example for writing to server response streams. #### `inOptions` (object) - Optional - **Description**: An object to configure PDF creation options. - **`version`** (number) - The desired PDF version (1.0 to 1.7). Defaults to 1.3 (PDF 1.3). Can use `hummus.ePDFVersionXX` constants. - **`compress`** (boolean) - If set to `false`, disables Flate compression for PDF streams. Defaults to `true`. - **`log`** (string) - A file path for logging internal library notes during debugging. Note: Enabling logging makes the module non-thread-safe. ### Returns - **PDFWriter object**: An object used for adding pages and content to the PDF. ``` -------------------------------- ### Creating a PDFReader Object Source: https://github.com/julianhille/muhammarajs/blob/develop/docs/Parsing.md Demonstrates how to create a PDFReader object for a given PDF file using the muhammara module. ```APIDOC ## Creating a PDFReader Object ### Description This section explains how to create a parser object, referred to as a PDFReader, for a regular PDF file. ### Method `muhammara.createReader(filePath)` ### Endpoint N/A (This is a library function, not a network endpoint) ### Parameters #### Path Parameters - **filePath** (string) - Required - The path to the PDF file to be read. ### Request Example ```javascript var muhammara = require("muhammara"); var pdfReader = muhammara.createReader("./TestMaterials/XObjectContent.PDF"); ``` ### Response - **pdfReader** (object) - A PDFReader object if the PDF is valid, otherwise an error may be thrown. ``` -------------------------------- ### Create a New PDF Document Source: https://github.com/julianhille/muhammarajs/blob/develop/README.md Initializes a new PDF document with metadata and creates a single page. ```javascript const Recipe = require("muhammara").Recipe; const pdfDoc = new Recipe("new", "output.pdf", { version: 1.6, author: "John Doe", title: "Hummus Recipe", subject: "A brand new PDF", }); pdfDoc.createPage("letter").endPage().endPDF(); ``` -------------------------------- ### Get Write Stream for PDF Stream Source: https://github.com/julianhille/muhammarajs/wiki/Extensibility Retrieve a ByteWriter stream object from a PDF stream context, used for writing the actual stream data. ```javascript streamCxt.getWriteStream() ``` -------------------------------- ### Modify an Existing PDF with MuhammaraJS Source: https://context7.com/julianhille/muhammarajs/llms.txt Use `createWriterToModify` to open an existing PDF for incremental updates. This example shows how to add text to an existing page. ```javascript const muhammara = require('muhammara'); // Modify existing PDF (overwrites original) const pdfWriter = muhammara.createWriterToModify('./existing.pdf'); // Or save to a different file const pdfWriter2 = muhammara.createWriterToModify('./existing.pdf', { modifiedFilePath: './modified.pdf' }); // Use PDFPageModifier to add content to existing pages const pageModifier = new muhammara.PDFPageModifier(pdfWriter, 0, true); pageModifier.startContext(); const ctx = pageModifier.getContext(); const font = pdfWriter.getFontForFile('./fonts/Helvetica.ttf'); ctx.writeText('Added text on existing page', 100, 500, { font: font, size: 14, colorspace: 'rgb', color: 0xFF0000 }); pageModifier.endContext().writePage(); pdfWriter.end(); ``` -------------------------------- ### Create and Use JPG Image XObject Source: https://github.com/julianhille/muhammarajs/blob/develop/docs/Show-images.md Create an image XObject from a JPG file path and place it on a PDF page. Ensure no context is active when creating the XObject. Use `q`, `Q`, and `cm` operators for graphic state management and scaling. ```javascript var imageXObject = pdfWriter.createImageXObjectFromJPG( "./TestMaterials/images/otherStage.JPG", ); var cxt = pdfWriter.startPageContentContext(page); cxt.q().cm(500, 0, 0, 400, 0, 0).doXObject(imageXObject).Q(); ``` -------------------------------- ### Writing PDF Primitives Source: https://github.com/julianhille/muhammarajs/blob/develop/docs/Extensibility.md Utilize the Objects Context methods to write various basic PDF primitive types. ```APIDOC ## PDF Primitives ### Description Methods for writing basic PDF primitive data types using the Objects Context. ### Methods - `writeName(inName)` - `writeLiteralString(inString/Array[bytes])` - `writeHexString(inString/Array[bytes])` - `writeBoolean(inBoolean)` - `writeKeyword(inKeyword)` - `writeComment(inComment)` - `writeNumber(inNumber)` - `writeIndirectObjectReference(inObjectID,[inGenerationNumber])` - `endLine()` ### Endpoint N/A (Methods of the Objects Context object) ### Parameters - **inName** (string) - The name to write (will be prefixed with '/'). - **inString/Array[bytes]** (string or Array) - The string or byte array to write as a literal or hex string. - **inBoolean** (boolean) - The boolean value to write. - **inKeyword** (string) - The PDF keyword (command) to write. - **inComment** (string) - The comment string to write. - **inNumber** (number) - The number to write. - **inObjectID** (number) - The ID of the object to reference. - **inGenerationNumber** (number) - Optional. The generation number for the object reference. ### Request Example ```javascript // Assuming objCxt is obtained via pdfWriter.getObjectsContext() // Writing various primitives objCxt.writeName('MyName'); objCxt.writeLiteralString('This is a literal string'); objCxt.writeHexString('0A1B2C'); objCxt.writeBoolean(true); objCxt.writeNumber(123.45); objCxt.writeComment('This is a PDF comment'); objCxt.writeIndirectObjectReference(5); // Reference object with ID 5 // Writing a keyword (e.g., endobj) - moves to next line objCxt.writeKeyword('endobj'); // Forcing a newline objCxt.endLine(); ``` ### Response These methods do not return a value but write the corresponding PDF representation to the object stream. Most methods add a space after the written primitive, except `writeKeyword` which assumes a command and moves to the next line. `endLine()` explicitly forces a newline. ``` -------------------------------- ### Get Source Document Page Count Source: https://github.com/julianhille/muhammarajs/wiki/Embedding-pdf Access the source document parser via the copying context to obtain the total number of pages in the source PDF. ```javascript cpyCxt.getSourceDocumentParser().getPagesCount() ``` -------------------------------- ### Create and Modify PDFs Using Buffers in Node.js Source: https://context7.com/julianhille/muhammarajs/llms.txt Demonstrates creating a new PDF and modifying an existing one entirely in memory using Node.js Buffers. Requires 'muhammara' and 'fs' modules. ```javascript const { Recipe } = require('muhammara'); const fs = require('fs'); // Create PDF and get as Buffer const pdfDoc = new Recipe(Buffer.from('new'), null, { title: 'Buffer PDF' }); const buffer = pdfDoc .createPage('letter') .text('PDF created from buffer', 100, 100, { fontSize: 16 }) .circle(300, 300, 50, { fill: '#3366cc' }) .endPage() .endPDF(); // Returns Buffer when no output file specified // Write buffer to file fs.writeFileSync('./from-buffer.pdf', buffer); // Modify existing PDF from buffer const existingBuffer = fs.readFileSync('./existing.pdf'); const modifiedDoc = new Recipe(existingBuffer, './modified.pdf'); modifiedDoc .editPage(1) .text('Added via buffer modification', 100, 50, { color: '#ff0000', fontSize: 12 }) .endPage() .endPDF(); ``` -------------------------------- ### Objects Context and Indirect Object Creation Source: https://github.com/julianhille/muhammarajs/blob/develop/docs/Extensibility.md Learn how to obtain the Objects Context and manage the creation of indirect PDF objects. ```APIDOC ## Objects Context Management ### Description Obtain the Objects Context from a PDFWriter object to manage the creation of PDF objects. ### Method `pdfWriter.getObjectsContext()` ### Endpoint N/A (Method within a PDFWriter instance) ### Parameters None ### Request Example ```javascript var objCxt = pdfWriter.getObjectsContext(); ``` ### Response Returns the Objects Context object. --- ## Indirect Object Creation ### Description Methods for starting and ending indirect object writing, and allocating object IDs. ### Methods - `startNewIndirectObject([inObjectID])` - `endIndirectObject()` - `allocateNewObjectID()` ### Endpoint N/A (Methods of the Objects Context object) ### Parameters - **inObjectID** (number) - Optional - The ID to assign to the new indirect object. If not provided, a new ID is allocated. ### Request Example ```javascript // Allocate an ID and then start a new indirect object with that ID var newObjectID = objCxt.allocateNewObjectID(); objCxt.startNewIndirectObject(newObjectID); // ... write object content ... objCxt.endIndirectObject(); // Start a new indirect object with an automatically allocated ID objCxt.startNewIndirectObject(); // ... write object content ... objCxt.endIndirectObject(); ``` ### Response - `startNewIndirectObject`: Returns the allocated object ID if no argument was provided. - `allocateNewObjectID`: Returns a new, unique object ID. ``` -------------------------------- ### Creating a PDFReader Object Source: https://github.com/julianhille/muhammarajs/wiki/Parsing Demonstrates how to create a PDFReader (parser) object for a given PDF file using the hummus.createReader method. ```APIDOC ## Creating a PDFReader Object ### Description Instantiate a PDFReader object to parse a PDF file. This object provides access to various PDF properties and content. ### Method `hummus.createReader(pdfFilePath)` ### Endpoint N/A (This is a library function, not a network endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript var hummus = require('hummus'); var pdfReader = hummus.createReader('./TestMaterials/XObject.PDF'); ``` ### Response Returns a PDFReader object if the PDF is valid and readable. Otherwise, an error may be thrown. #### Success Response (200) - **pdfReader** (object) - The created PDFReader object. #### Response Example (No specific response body, returns the object directly) ``` -------------------------------- ### Define and Use a Form XObject Source: https://github.com/julianhille/muhammarajs/blob/develop/docs/Reusable-forms.md Create a Form XObject, define its content, and then place it on a PDF page. This is useful for reusing complex graphics without duplicating drawing commands. ```javascript // define a form var xobjectForm = pdfWriter.createFormXObject(0, 0, 200, 100); xobjectForm .getContentContext() .q() .k(0, 100, 100, 0) .re(0, 0, 200, 100) .f() .Q(); pdfWriter.endFormXObject(xobjectForm); // start a page var page = pdfWriter.createPage(0, 0, 595, 842); var pageContent = pdfWriter.startPageContentContext(page); // draw some graphics using the form pageContent.q().cm(1, 0, 0, 1, 200, 600).doXObject(xobjectForm).Q(); ``` -------------------------------- ### Get Image Dimensions Source: https://github.com/julianhille/muhammarajs/wiki/Show-images Retrieve the width and height of an image using the `getImageDimensions` method of the `PDFWriter` object. This is useful for tasks like drawing frames or fitting images. ```javascript var jpgDimensions = pdfWriter.getImageDimensions('./TestMaterials/Images/soundcloud_logo.jpg'); ``` -------------------------------- ### Get Page Box Dimensions Source: https://github.com/julianhille/muhammarajs/blob/develop/docs/Parsing.md Retrieve the dimensions of various boxes associated with a PDF page. These methods return an array of four numbers: [left, bottom, right, top]. ```javascript getMediaBox(); getCropBox(); getTrimBox(); getBleedBox(); getArtBox(); ``` -------------------------------- ### Create New Indirect Object in Hummus Source: https://github.com/julianhille/muhammarajs/blob/develop/docs/Extensibility.md Starts writing a new indirect object. Call with no arguments to auto-generate an ID, or pass a pre-allocated ID. Ensure to call endIndirectObject() after writing content. ```javascript startNewIndirectObject([inObjectID]); ``` -------------------------------- ### Initialize Hummus PDF Writer Source: https://github.com/julianhille/muhammarajs/wiki/How-to-serve-dynamically-created-pdf Initializes the Hummus PDF writer using a custom stream for the Express response object. ```javascript var hummus = require('hummus'); var pdfWriter = hummus.createWriter(new hummus.PDFStreamForResponse(res)); ``` -------------------------------- ### PDF Text Positioning Operators Source: https://github.com/julianhille/muhammarajs/blob/develop/docs/Use-the-pdf-drawing-operators.md Operators for manipulating the text matrix and positioning text on the page. Includes moving to a new line, setting the text matrix, and moving to the start of the next line. ```javascript // Text positioning operators Td(inTx,inTy); TD(inTx,inTy); Tm(inA,inB, inC, inD, inE, inF); TStar(); // equivalent to T* ``` -------------------------------- ### Get Modified File Parser - JavaScript Source: https://github.com/julianhille/muhammarajs/blob/develop/docs/Modification.md Use getModifiedFileParser to obtain a parser for existing parts of a PDF file during modification. This parser functions like a regular parser for reading file content. ```javascript getModifiedFileParser(); ``` -------------------------------- ### Create PDF Reader Object Source: https://github.com/julianhille/muhammarajs/wiki/Parsing Instantiate a PDF reader (parser) object for a given PDF file. Ensure the file path is correct. ```javascript var hummus = require('hummus'); var pdfReader = hummus.createReader('./TestMaterials/XObject.PDF'); ``` -------------------------------- ### Start Modified Indirect Object - JavaScript Source: https://github.com/julianhille/muhammarajs/blob/develop/docs/Modification.md Use objCxt.startModifiedIndirectObject(inObjectID) to begin defining a modified indirect object, specifying the existing object ID. The original object is ignored once the modified definition is complete. ```javascript objCxt.startModifiedIndirectObject(inObjectID); ``` -------------------------------- ### Create New PDF with Multiple Pages Source: https://context7.com/julianhille/muhammarajs/llms.txt Use the Recipe class to create a new PDF document. Specify metadata and add multiple pages with text and shapes. Ensure to call endPage() after each page and endPDF() to finalize the document. ```javascript const { Recipe } = require('muhammara'); // Create new PDF const pdfDoc = new Recipe('new', './output.pdf', { version: 1.7, author: 'John Doe', title: 'Sample Document', subject: 'Recipe API Demo', keywords: ['pdf', 'muhammara', 'recipe'] }); // Create first page (letter size) pdfDoc .createPage('letter') .text('Welcome to MuhammaraJS Recipe', 'center', 50, { color: '#003366', fontSize: 28, bold: true, align: 'center center' }) .text('Easy PDF generation with chainable methods', 100, 120, { color: '#666666', fontSize: 14 }) .rectangle(50, 160, 500, 2, { fill: '#003366' }) .endPage() // Create second page (A4) .createPage('A4') .text('Page 2 content here', 100, 100) .endPage() .endPDF(); console.log('PDF created successfully'); ``` -------------------------------- ### Retrieving Copied Object IDs Source: https://github.com/julianhille/muhammarajs/wiki/Embedding-pdf Obtain the new ID of a copied object in the target PDF using `getCopiedObjectID`. To get a mapping of all source object IDs to their corresponding target IDs, call `getCopiedObjects`. ```javascript cpyCxt.getCopiedObjectID(inSourceObjectID) cpyCxt.getCopiedObjects() ``` -------------------------------- ### Getting JavaScript Values from PDFObjects Source: https://github.com/julianhille/muhammarajs/wiki/Parsing Provides simple JavaScript value getters for quick retrieval of number or string representations from PDFObjects. `toNumber()` returns a number or null, while `toString()` returns a string representation. ```javascript toNumber() toString() ``` -------------------------------- ### Get Page Box Dimensions Source: https://github.com/julianhille/muhammarajs/wiki/Parsing Retrieve the dimensions of various page boxes (MediaBox, CropBox, TrimBox, BleedBox, ArtBox). Each method returns an array of four numbers: [left, bottom, right, top]. ```javascript getMediaBox() getCropBox() getTrimBox() getBleedBox() getArtBox() ``` -------------------------------- ### Write PDF to HTTP Response Stream with Muhammara.js Source: https://context7.com/julianhille/muhammarajs/llms.txt Shows how to create a PDF dynamically and stream it directly to an HTTP response using Node.js. This avoids saving the PDF to a file on the server. Requires setting appropriate response headers. ```javascript const muhammara = require('muhammara'); const http = require('http'); const server = http.createServer((req, res) => { // Set PDF headers res.writeHead(200, { 'Content-Type': 'application/pdf', 'Content-Disposition': 'inline; filename="generated.pdf"' }); // Create PDF writer to response stream const pdfWriter = muhammara.createWriter( new muhammara.PDFStreamForResponse(res) ); const page = pdfWriter.createPage(0, 0, 595, 842); const ctx = pdfWriter.startPageContentContext(page); const font = pdfWriter.getFontForFile('./fonts/Helvetica.ttf'); ctx.writeText('Dynamically Generated PDF', 100, 700, { font: font, size: 24, colorspace: 'rgb', color: 0x000000 }); pdfWriter.writePage(page); pdfWriter.end(); res.end(); }); server.listen(3000); console.log('PDF server running on http://localhost:3000'); ``` -------------------------------- ### Create and Use JPG Image XObject Source: https://github.com/julianhille/muhammarajs/wiki/Show-images Create an image XObject from a JPG file and place it on a PDF page. Ensure no context is active when creating the XObject. ```javascript var imageXObject = pdfWriter.createImageXObjectFromJPG('./TestMaterials/images/otherStage.JPG'); var cxt = pdfWriter.startPageContentContext(page); cxt.q() .cm(500,0,0,400,0,0) .doXObject(imageXObject) .Q(); ``` -------------------------------- ### Get Modified Input File - JavaScript Source: https://github.com/julianhille/muhammarajs/blob/develop/docs/Modification.md Retrieve an InputFile object using getModifiedInputFile to access the source file stream and path when working with a modified file. This is useful for reading the original file's data. ```javascript getModifiedInputFile(); ``` -------------------------------- ### Get Font for File Source: https://github.com/julianhille/muhammarajs/wiki/Show-text Obtain a font object by providing the path to a font file. Supports TTF, OTF, PFB/PFM, DFONT, and TTC formats. For font collections like DFONT and TTC, an optional font index can be provided. ```javascript var arialFont = pdfWriter.getFontForFile('./TestMaterials/fonts/arial.ttf'); ``` -------------------------------- ### Configure Include Directories for LibAesgm Source: https://github.com/julianhille/muhammarajs/blob/develop/src/deps/LibAesgm/CMakeLists.txt Sets the include directories for the LibAesgm library. It specifies interface include directories for build-time and installation-time. ```cmake target_include_directories(LibAesgm INTERFACE $ $ ) ``` -------------------------------- ### Get Source Document Parser and Stream Source: https://github.com/julianhille/muhammarajs/blob/develop/docs/Embedding-pdf.md Access the source document's parser or stream from the copying context. The parser provides high-level information and access to low-level PDF building blocks, while the stream allows direct byte reading. ```javascript cpyCxt.getSourceDocumentParser(); ``` ```javascript cpyCxt.getSourceDocumentStream(); ``` -------------------------------- ### Font Handling and Text Measurement in MuhammaraJS Source: https://context7.com/julianhille/muhammarajs/llms.txt Illustrates loading various font types (TrueType, Type 1, collections) and measuring text dimensions for precise placement and layout. Requires 'muhammara'. ```javascript const muhammara = require('muhammara'); const pdfWriter = muhammara.createWriter('./font-demo.pdf'); // Load various font types const arial = pdfWriter.getFontForFile('./fonts/arial.ttf'); const times = pdfWriter.getFontForFile('./fonts/times.ttf'); const courier = pdfWriter.getFontForFile('./fonts/cour.ttf'); // For Type 1 fonts, provide both files const type1 = pdfWriter.getFontForFile('./fonts/font.pfb', './fonts/font.pfm'); // For font collections (ttc, dfont), specify index const japanese = pdfWriter.getFontForFile('./fonts/collection.ttc', 1); // Measure text before drawing const text = 'Sample Text for Measurement'; const fontSize = 24; const dims = arial.calculateTextDimensions(text, fontSize); console.log('Text dimensions:', { width: dims.width, height: dims.height, xMin: dims.xMin, yMin: dims.yMin, xMax: dims.xMax, yMax: dims.yMax }); // Use measurements for centered text const page = pdfWriter.createPage(0, 0, 595, 842); const ctx = pdfWriter.startPageContentContext(page); const pageWidth = 595; const xPos = (pageWidth - dims.width) / 2; ctx.writeText(text, xPos, 700, { font: arial, size: fontSize, colorspace: 'rgb', color: 0x000000 }); // Draw bounding box around text ctx.drawRectangle(xPos + dims.xMin, 700 + dims.yMin, dims.width, dims.height, { type: 'stroke', colorspace: 'rgb', color: 0xFF0000, width: 0.5 }); pdfWriter.writePage(page); pdfWriter.end(); ``` -------------------------------- ### Create a Content Context Source: https://github.com/julianhille/muhammarajs/wiki/Show-primitives Before drawing any content on a PDF page, you need to create a content context for it. This is done by calling `startPageContentContext` with the page object. ```APIDOC ## Create a Context To place any content on a page, you must first create a content context for it. You do so by using the following code: ```javascript var cxt = pdfWriter.startPageContentContext(page); ``` Pass a page to `startPageContentContext` and you should be ready. The content context object can now be used to place content on a page. ``` -------------------------------- ### Create PDF Copying Context Source: https://github.com/julianhille/muhammarajs/wiki/Embedding-pdf Create a PDF copying context from a source PDF file or stream. This context allows for flexible manipulation of PDF content. ```javascript var cpyCxt = pdfWriter.createPDFCopyingContext(inSourceFilePDF || inSourceFileStream) ``` -------------------------------- ### Create JPG Form XObject Source: https://github.com/julianhille/muhammarajs/wiki/Show-images Create a form XObject from a JPG file. This form is already scaled to the image dimensions and can be reused. ```javascript var formXObject = pdfWriter.createFormXObjectFromJPG('./TestMaterials/images/otherStage.JPG'); ``` -------------------------------- ### Embed Images in PDF with Muhammara.js Source: https://context7.com/julianhille/muhammarajs/llms.txt Demonstrates how to embed JPG, PNG, and TIFF images, as well as PDF pages, into a PDF document. Supports basic placement, scaling, and fitting to bounding boxes. Also shows how to retrieve image dimensions. ```javascript const muhammara = require('muhammara'); const pdfWriter = muhammara.createWriter('./with-images.pdf'); const page = pdfWriter.createPage(0, 0, 595, 842); const ctx = pdfWriter.startPageContentContext(page); // Simple image placement at coordinates ctx.drawImage(50, 700, './photo.jpg'); ctx.drawImage(50, 500, './logo.png'); ctx.drawImage(50, 300, './scan.tif'); // Embed PDF page as image ctx.drawImage(300, 700, './other.pdf', { index: 0 }); // Image with transformation (scaling) ctx.drawImage(300, 500, './photo.jpg', { transformation: [0.5, 0, 0, 0.5, 0, 0] // Scale to 50% }); // Fit image to bounding box ctx.drawImage(300, 300, './photo.jpg', { transformation: { width: 200, height: 200, proportional: true, fit: 'always' } }); // Get image dimensions before placing const dims = pdfWriter.getImageDimensions('./photo.jpg'); console.log('Image size:', dims.width, 'x', dims.height); pdfWriter.writePage(page); pdfWriter.end(); ``` -------------------------------- ### Implement Custom Read Stream Interface Source: https://github.com/julianhille/muhammarajs/wiki/Custom-streams Custom read streams require several methods for random access and stream management. Implement `read`, `notEnded`, `setPosition`, `setPositionFromEnd`, `skip`, and `getCurrentPosition` to enable reading from custom sources. ```javascript read(inAmount), returns an array of bytes read from the current position in the stream, that contains up to inAmount bytes. notEnded(), returns a boolean specifying whether the stream is finished or not. setPosition(inPosition), set the read cursor position to the input position, from the start of the stream setPositionFromEnd(inPosition), set the read cursor position to the input position, from the end of the stream skip(inAmount), skip inAmount number of bytes. getCurrentPosition(), get the current read position in the stream. ``` -------------------------------- ### Path Construction Operators Source: https://github.com/julianhille/muhammarajs/wiki/Use-the-pdf-drawing-operators Define paths using commands like 'm' (moveto), 'l' (lineto), 'c' (curveto), 'v', 'y', 'h' (closepath), and 're' (rectangle). Parameters are typically numbers representing coordinates. ```javascript m(inX,inY); ``` ```javascript l(inX,inY); ``` ```javascript c(inX1,inY1,inX2,inY2,inX3,inY3); ``` ```javascript v(inX2,inY2,inX3,inY3); ``` ```javascript y(inX1,inY1,inX3,inY3); ``` ```javascript h(); ``` ```javascript re(inLeft,inBottom,inWidth,inHeight); ``` -------------------------------- ### Create a Content Context Source: https://github.com/julianhille/muhammarajs/blob/develop/docs/Show-primitives.md Before drawing any content, you need to create a content context associated with a specific page. ```APIDOC ## Create a context To place any content on a page, you must first create a content context for it. You do so by using the following code: ```javascript var cxt = pdfWriter.startPageContentContext(page); ``` Pass a page to `startPageContentContext` and you should be ready. The content context object can now be used to place content on a page. ``` -------------------------------- ### Draw Simple Images Source: https://github.com/julianhille/muhammarajs/blob/develop/docs/Show-images.md Use the `drawImage` method to place JPG, TIFF, PNG, and PDF files on a page. Coordinates specify the bottom-left corner. Custom stream input is not supported for basic drawing. ```javascript var cxt = pdfWriter.startPageContentContext(page); // simple image placement cxt .drawImage(10, 10, "./TestMaterials/Images/soundcloud_logo.jpg") .drawImage(10, 500, "./TestMaterials/images/tiff/cramps.tif") .drawImage(200, 500, "./TestMaterials/images/png/original.png") .drawImage(0, 0, "./TestMaterials/XObjectContent.PDF"); ``` -------------------------------- ### Create a New PDF as a Buffer Source: https://github.com/julianhille/muhammarajs/blob/develop/README.md Generates a new PDF document and returns its content as a Buffer instead of saving it to a file. ```javascript const Recipe = require("muhammara").Recipe; const pdfDoc = new Recipe(Buffer.from("new"), null, { version: 1.6, author: "John Doe", title: "Hummus Recipe", subject: "A brand new PDF", }); const pdfBuffer = pdfDoc.createPage("letter").endPage().endPDF(); ``` -------------------------------- ### Write Text with Options Source: https://github.com/julianhille/muhammarajs/blob/develop/docs/Show-text.md Use this method to write text at specific coordinates with customizable options. Ensure you have a page content context and a font object. ```javascript cxt.writeText(text, x, y, [{ options }]); var textOptions = { font: arialFont, size: 14, colorspace: "gray", color: 0x00, }; cxt.writeText("Paths", 75, 805, textOptions); ``` -------------------------------- ### Create and Use a PDF Form XObject Source: https://github.com/julianhille/muhammarajs/wiki/Reusable-forms Define a reusable graphic form, add drawing commands to it, and then place it on a PDF page. This is useful for repeating complex graphics without increasing file size. ```javascript // define a form var xobjectForm = pdfWriter.createFormXObject(0,0,200,100); xobjectForm.getContentContext().q() .k(0,100,100,0) .re(0,0,200,100) .f() .Q(); pdfWriter.endFormXObject(xobjectForm); // start a page var page = pdfWriter.createPage(0,0,595,842); var pageContent = pdfWriter.startPageContentContext(page); // draw some graphics using the form pageContent.q() .cm(1,0,0,1,200,600) .doXObject(xobjectForm) .Q(); ```