### Install Presa Go SDK Source: https://docs.presa.dev/getting-started/quickstart Installs the Presa SDK for Go using the go get command. This package is used for generating PDFs within Go applications. ```go go get github.com/faiscadev/presa-go ``` -------------------------------- ### Generate PDF - Go Source: https://docs.presa.dev/getting-started/quickstart Example of generating a PDF using the Presa Go SDK. ```APIDOC ## Generate PDF - Go ### Description This endpoint generates a PDF document from HTML content using the Presa Go SDK. ### Method POST ### Endpoint https://api.presa.dev/v1/pdf/from-html (Implicit via SDK) ### Parameters #### Request Body - **html** (string) - Required - The HTML content to convert to PDF. ### Request Example ```go package main import ( context "context" "os" presa "github.com/faiscadev/presa-go" ) func main() { result, err := presa.Generate(context.Background(), presa.Options{ HTML: "

Hello World

Generated with Presa.

", }) if err != nil { panic(err) } os.WriteFile("output.pdf", result.Buffer, 0644) } ``` ### Response #### Success Response (200) - **Buffer** ([]byte) - The binary content of the generated PDF. #### Response Example (Binary PDF data written to file) ``` -------------------------------- ### Generate PDF - Python Source: https://docs.presa.dev/getting-started/quickstart Example of generating a PDF using the Presa library in Python. ```APIDOC ## Generate PDF - Python ### Description This endpoint generates a PDF document from HTML content using the Presa library for Python. ### Method POST ### Endpoint https://api.presa.dev/v1/pdf/from-html (Implicit via Library) ### Parameters #### Request Body - **html** (string) - Required - The HTML content to convert to PDF. ### Request Example ```python from presa import PDF result = PDF.generate(html="

Hello World

Generated with Presa.

") with open("output.pdf", "wb") as f: f.write(result.buffer) ``` ### Response #### Success Response (200) - **buffer** (bytes) - The binary content of the generated PDF. #### Response Example (Binary PDF data written to file) ``` -------------------------------- ### Get an API Key Source: https://docs.presa.dev/getting-started/quickstart Instructions on how to obtain your Presa API key by signing up on the Presa dashboard. ```APIDOC ## Get an API Key ### Description Sign up at app.presa.dev and copy your API key from the dashboard. ### Method GET (Implicit - User Action Required) ### Endpoint https://app.presa.dev/dashboard ### Parameters None ### Request Example None ### Response - **API Key** (string) - Your unique API key for authentication. ``` -------------------------------- ### Install Presa Go SDK and Gin Source: https://docs.presa.dev/frameworks/gin Installs the necessary Presa Go SDK and Gin framework packages using the go get command. Ensure you have Go installed and configured. ```go go get github.com/faiscadev/presa-go go get github.com/gin-gonic/gin ``` -------------------------------- ### Generate PDF - Node.js / TypeScript Source: https://docs.presa.dev/getting-started/quickstart Example of generating a PDF using the Presa SDK in Node.js or TypeScript. ```APIDOC ## Generate PDF - Node.js / TypeScript ### Description This endpoint generates a PDF document from HTML content using the Presa SDK for Node.js and TypeScript. ### Method POST ### Endpoint https://api.presa.dev/v1/pdf/from-html (Implicit via SDK) ### Parameters #### Request Body - **html** (string) - Required - The HTML content to convert to PDF. ### Request Example ```javascript import { writeFileSync } from "fs"; import { PDF } from "presa-sdk"; const { buffer } = await PDF.generate({ html: "

Hello World

Generated with Presa.

", }); // buffer is a Uint8Array containing the PDF writeFileSync("output.pdf", buffer); ``` ### Response #### Success Response (200) - **buffer** (Uint8Array) - The binary content of the generated PDF. #### Response Example (Binary PDF data written to file) ``` -------------------------------- ### Quick Start Source: https://docs.presa.dev/sdks/go A basic example demonstrating how to use the `presa.Generate` function to convert HTML to PDF. The API key is automatically read from the environment. ```APIDOC ## Quick Start ### Description A basic example demonstrating how to use the `presa.Generate` function to convert HTML to PDF. The API key is automatically read from the environment. ### Method N/A (Function call) ### Endpoint N/A ### Parameters N/A ### Request Example ```go package main import ( "context" "fmt" "os" presa "github.com/faiscadev/presa-go" ) func main() { result, err := presa.Generate(context.Background(), presa.Options{ HTML: "

Invoice #1234

Total: $99.00

", }) if err != nil { fmt.Fprintf(os.Stderr, "Error: %v\n", err) os.Exit(1) } fmt.Printf("Generated %d bytes\n", result.Size) os.WriteFile("output.pdf", result.Buffer, 0644) } ``` ### Response #### Success Response (200) - **Size** (int) - The size of the generated PDF in bytes. - **Buffer** ([]byte) - The byte buffer containing the PDF content. #### Response Example ```json { "Size": 12345, "Buffer": "...pdf content..." } ``` ``` -------------------------------- ### Install Presa SDK and Configure API Key Source: https://docs.presa.dev/frameworks/nextjs Installs the Presa SDK using npm and configures the necessary API key in the .env.local file. This is the initial setup step for using the SDK. ```bash npm install presa-sdk ``` ```env PRESA_API_KEY=your-api-key ``` -------------------------------- ### Generate PDF - cURL Source: https://docs.presa.dev/getting-started/quickstart Example of generating a PDF using cURL by making a direct API request. ```APIDOC ## Generate PDF - cURL ### Description This endpoint generates a PDF document from HTML content using a direct cURL request to the Presa API. ### Method POST ### Endpoint https://api.presa.dev/v1/pdf/from-html ### Parameters #### Headers - **Authorization** (string) - Required - Bearer token with your API key (e.g., "Bearer $PRESA_API_KEY"). - **Content-Type** (string) - Required - Set to "application/json". #### Request Body - **html** (string) - Required - The HTML content to convert to PDF. ### Request Example ```bash curl -X POST https://api.presa.dev/v1/pdf/from-html \ -H "Authorization: Bearer $PRESA_API_KEY" \ -H "Content-Type: application/json" \ -d '{"html": "

Hello World

"}' \ -o output.pdf ``` ### Response #### Success Response (200) - **Output** (file) - The generated PDF file is saved as 'output.pdf'. #### Response Example (Binary PDF data written to file) ``` -------------------------------- ### Install Presa Go SDK Source: https://docs.presa.dev/sdks/go Installs the Presa Go SDK using the go get command. Requires Go version 1.21 or later and has no external dependencies. ```go go get github.com/faiscadev/presa-go ``` -------------------------------- ### Quick Start: PDF Generation Source: https://docs.presa.dev/sdks/nodejs A quick start guide demonstrating how to generate a PDF from HTML content using the `PDF.generate()` convenience function. It automatically reads the `PRESA_API_KEY` from the environment. ```APIDOC ## Quick start ```typescript import { PDF } from "presa-sdk"; const { buffer, size } = await PDF.generate({ html: "

Invoice #1234

Total: $99.00

", }); console.log(`Generated ${size} bytes`); ``` The `PDF.generate()` convenience function reads `PRESA_API_KEY` from the environment automatically. ``` -------------------------------- ### Install Presa Python SDK Source: https://docs.presa.dev/frameworks/fastapi Installs the Presa Python SDK along with FastAPI and Uvicorn for running the web server. This is the initial setup step for using Presa with FastAPI. ```bash pip install presa fastapi uvicorn ``` -------------------------------- ### Installation Source: https://docs.presa.dev/sdks/go Instructions on how to install the Presa Go SDK. Requires Go 1.21+ and has no external dependencies. ```APIDOC ## Installation ### Description Instructions on how to install the Presa Go SDK. Requires Go 1.21+ and has no external dependencies. ### Method N/A (Installation command) ### Endpoint N/A ### Parameters N/A ### Request Example ```bash go get github.com/faiscadev/presa-go ``` ### Response N/A ``` -------------------------------- ### Install Presa SDK Source: https://docs.presa.dev/guides/puppeteer-migration This command installs the Presa SDK and optionally uninstalls the Puppeteer package. It's a crucial step for migrating from Puppeteer to Presa. ```bash npm install presa-sdk npm uninstall puppeteer # optional ``` -------------------------------- ### Generate PDF using Presa in Go Source: https://docs.presa.dev/getting-started/quickstart Generates a PDF from HTML content using the Presa SDK in Go. It takes an HTML string and writes the PDF buffer to 'output.pdf'. Requires the 'presa-go' package. ```go package main import ( "context" "os" presa "github.com/faiscadev/presa-go" ) func main() { result, err := presa.Generate(context.Background(), presa.Options{ HTML: "

Hello World

Generated with Presa.

", }) if err != nil { panic(err) } os.WriteFile("output.pdf", result.Buffer, 0644) } ``` -------------------------------- ### Set Environment Variable Source: https://docs.presa.dev/getting-started/quickstart How to set the Presa API key as an environment variable for use in your applications. ```APIDOC ## Set Environment Variable ### Description Set your Presa API key as an environment variable to authenticate your requests. ### Method Environment Variable Configuration ### Endpoint N/A ### Parameters - **PRESA_API_KEY** (string) - Required - Your Presa API key. ### Request Example ```bash export PRESA_API_KEY="your-api-key" ``` ### Response None ``` -------------------------------- ### Installation Source: https://docs.presa.dev/sdks/nodejs Instructions for installing the Presa SDK using npm. Requires Node.js 18+ and has zero peer dependencies. ```APIDOC ## Installation ```bash npm install presa-sdk ``` Requires Node.js 18+. Zero peer dependencies. ``` -------------------------------- ### Generate PDF from HTML using cURL Source: https://docs.presa.dev/getting-started/quickstart Generates a PDF from HTML content using a cURL command. This example sends a POST request to the Presa API with JSON payload containing HTML and saves the output to 'output.pdf'. It requires the PRESA_API_KEY environment variable to be set. ```bash curl -X POST https://api.presa.dev/v1/pdf/from-html \ -H "Authorization: Bearer $PRESA_API_KEY" \ -H "Content-Type: application/json" \ -d '{"html": "

Hello World

"}' \ -o output.pdf ``` -------------------------------- ### Create Presa Go SDK Client Instance Source: https://docs.presa.dev/sdks/go Demonstrates how to create a custom Presa client instance for more granular control over PDF generation. Allows specifying API key, base URL, and timeout. Includes an example of generating a PDF with custom options like format, orientation, and margins. ```go import ( "context" "log" "time" presa "github.com/faiscadev/presa-go" ) client, err := presa.NewClient(&presa.Config{ APIKey: "your-api-key", // or set PRESA_API_KEY env var BaseURL: "https://api.presa.dev", // default Timeout: 30 * time.Second, // default }) if err != nil { log.Fatal(err) } landscape := true ctx := context.Background() result, err := client.Generate(ctx, presa.Options{ HTML: "

Hello

", Format: "A4", Landscape: &landscape, Margins: &presa.Margins{Top: "1cm", Right: "1cm", Bottom: "1cm", Left: "1cm"}, }) ``` -------------------------------- ### Generate PDF using Playwright (Before) and Presa (After) Source: https://docs.presa.dev/guides/puppeteer-migration Compares PDF generation between Playwright and Presa. The Playwright example shows launching a browser, creating a page, setting content, and generating a PDF. The Presa example demonstrates a more streamlined approach using `PDF.generate`. ```javascript // Before (Playwright) const browser = await chromium.launch(); const page = await browser.newPage(); await page.setContent(html); const pdf = await page.pdf({ format: "A4" }); await browser.close(); // After (Presa) import { PDF } from "presa-sdk"; const { buffer } = await PDF.generate({ html, format: "A4" }); ``` -------------------------------- ### Generate PDF using Presa in Python Source: https://docs.presa.dev/getting-started/quickstart Generates a PDF from HTML content using the Presa library in Python. It takes an HTML string and writes the PDF buffer to 'output.pdf'. Requires the 'presa' package. ```python from presa import PDF result = PDF.generate(html="

Hello World

Generated with Presa.

") with open("output.pdf", "wb") as f: f.write(result.buffer) ``` -------------------------------- ### Generate PDF from HTML using Presa Go SDK Source: https://docs.presa.dev/sdks/go Quick start example demonstrating how to generate a PDF from HTML content using the Presa Go SDK. It utilizes the `presa.Generate` function and writes the output to a file named 'output.pdf'. The API key is automatically read from the environment variable `PRESA_API_KEY`. ```go package main import ( "context" "fmt" "os" presa "github.com/faiscadev/presa-go" ) func main() { result, err := presa.Generate(context.Background(), presa.Options{ HTML: "

Invoice #1234

Total: $99.00

", }) if err != nil { fmt.Fprintf(os.Stderr, "Error: %v\n", err) os.Exit(1) } fmt.Printf("Generated %d bytes\n", result.Size) os.WriteFile("output.pdf", result.Buffer, 0644) } ``` -------------------------------- ### Install Presa SDK Source: https://docs.presa.dev/frameworks/remix Installs the Presa SDK using npm. This is the first step to enable PDF generation capabilities in your Remix project. ```bash npm install presa-sdk ``` -------------------------------- ### Install Presa SDK and Express Source: https://docs.presa.dev/frameworks/express Installs the necessary Presa SDK and Express packages using npm. This is the first step to integrating Presa into your Express application. ```bash npm install presa-sdk express ``` -------------------------------- ### Generate PDF using Presa SDK in Node.js/TypeScript Source: https://docs.presa.dev/getting-started/quickstart Generates a PDF from HTML content using the Presa SDK in Node.js or TypeScript. It takes an HTML string as input and writes the resulting PDF buffer to a file named 'output.pdf'. Requires the 'presa-sdk' package. ```javascript import { writeFileSync } from "fs"; import { PDF } from "presa-sdk"; const { buffer } = await PDF.generate({ html: "

Hello World

Generated with Presa.

", }); // buffer is a Uint8Array containing the PDF writeFileSync("output.pdf", buffer); ``` -------------------------------- ### Client Instance: Advanced PDF Generation Source: https://docs.presa.dev/sdks/nodejs Demonstrates how to create a `Presa` client instance for more control over PDF generation, including setting API keys, base URLs, and timeouts. Shows an example of generating a PDF with specific formatting options. ```APIDOC ## Client instance For more control, create a `Presa` client: ```typescript import { Presa } from "presa-sdk"; const client = new Presa({ apiKey: "your-api-key", // or set PRESA_API_KEY env var baseUrl: "https://api.presa.dev", // default timeout: 30000, // ms, default }); const result = await client.generate({ html: "

Hello

", format: "A4", landscape: false, margins: { top: "1cm", right: "1cm", bottom: "1cm", left: "1cm" }, printBackground: true, scale: 1.0, }); ``` ``` -------------------------------- ### Set Environment Variable for Presa API Key Source: https://docs.presa.dev/getting-started/quickstart This snippet demonstrates how to set the PRESA_API_KEY environment variable, which is required for authenticating with the Presa API. Ensure this variable is set in your environment before making API calls. ```bash export PRESA_API_KEY="your-api-key" ``` -------------------------------- ### Basic PDF Generation with Gin Source: https://docs.presa.dev/frameworks/gin Demonstrates a basic Gin handler for generating a PDF from HTML content. It expects a JSON payload with an 'html' field and returns the generated PDF. Requires the Presa Go SDK and Gin to be installed. ```go package main import ( "net/http" "github.com/gin-gonic/gin" presa "github.com/faiscadev/presa-go" ) func main() { client, err := presa.NewClient(nil) if err != nil { panic(err) } r := gin.Default() r.POST("/api/pdf", func(c *gin.Context) { var req struct { HTML string `json:"html" binding:"required"` } if err := c.ShouldBindJSON(&req); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } result, err := client.Generate(c.Request.Context(), presa.Options{ HTML: req.HTML, }) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "PDF generation failed"}) return } c.Header("Content-Disposition", `attachment; filename="document.pdf"`) c.Data(http.StatusOK, "application/pdf", result.Buffer) }) r.Run(":8080") } ``` -------------------------------- ### Install Presa Python SDK Source: https://docs.presa.dev/sdks/python Installs the Presa Python SDK using pip. This package has no external dependencies and requires Python 3.10+. ```bash pip install presa ``` -------------------------------- ### Generate PDF from HTML using convenience function Source: https://docs.presa.dev/sdks/nodejs Demonstrates the quick start method for generating a PDF from HTML using the `PDF.generate()` function. It automatically reads the `PRESA_API_KEY` from the environment and returns the PDF buffer and its size. ```typescript import { PDF } from "presa-sdk"; const { buffer, size } = await PDF.generate({ html: "

Invoice #1234

Total: $99.00

", }); console.log(`Generated ${size} bytes`); ``` -------------------------------- ### Example cURL Request for HTML to PDF Conversion Source: https://docs.presa.dev/api-reference/pdf-generation Demonstrates how to use cURL to send a POST request to the /v1/pdf/from-html endpoint. This example shows how to set the Authorization header, Content-Type, and provide a JSON payload with HTML content and formatting options. The output is saved to 'invoice.pdf'. ```bash curl -X POST https://api.presa.dev/v1/pdf/from-html \ -H "Authorization: Bearer $PRESA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "html": "

Invoice

Amount: $99.00

", "format": "Letter", "margins": {"top": "1in", "bottom": "1in"} }' \ -o invoice.pdf ``` -------------------------------- ### Handle Errors with Presa Go SDK Source: https://docs.presa.dev/sdks/go Provides a comprehensive example of error handling when using the Presa Go SDK. It shows how to differentiate between various error types such as authentication errors, API errors, and timeout errors using `errors.As`. ```go import ( "errors" "fmt" presa "github.com/faiscadev/presa-go" ) result, err := presa.Generate(context.Background(), presa.Options{HTML: html}) if err != nil { var authErr *presa.AuthenticationError var apiErr *presa.APIError var timeoutErr *presa.TimeoutError switch { case errors.As(err, &authErr): // Missing or invalid API key case errors.As(err, &apiErr): fmt.Println(apiErr.Code) // e.g., "QUOTA_EXCEEDED" fmt.Println(apiErr.Status) // e.g., 403 fmt.Println(apiErr.Message) // human-readable case errors.As(err, &timeoutErr): // Request took too long default: // Network or other error } } ``` -------------------------------- ### Generate PDF from HTML using Presa SDK Source: https://docs.presa.dev/sdks/python Demonstrates the quick start for generating a PDF from HTML using the `PDF.generate()` function. It automatically reads the `PRESA_API_KEY` from the environment and saves the generated PDF to a file. ```python from presa import PDF result = PDF.generate(html="

Invoice #1234

Total: $99.00

") print(f"Generated {result.size} bytes") with open("output.pdf", "wb") as f: f.write(result.buffer) ``` -------------------------------- ### Generate PDF using Puppeteer Source: https://docs.presa.dev/guides/puppeteer-migration This snippet demonstrates how to launch a Puppeteer browser instance, create a new page, set HTML content, and generate a PDF with specified formatting and margins. It requires the 'puppeteer' package and Node.js. ```javascript import puppeteer from "puppeteer"; const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.setContent("

Invoice #1234

Total: $99.00

"); const pdfBuffer = await page.pdf({ format: "A4", printBackground: true, margin: { top: "1cm", right: "1cm", bottom: "1cm", left: "1cm" }, }); await browser.close(); ``` -------------------------------- ### Generate PDF using Presa SDK Source: https://docs.presa.dev/guides/puppeteer-migration This snippet shows how to generate a PDF using the Presa SDK by providing HTML content and PDF generation options directly in the `PDF.generate` call. It requires the 'presa-sdk' package and an API key. ```javascript import { PDF } from "presa-sdk"; const { buffer } = await PDF.generate({ html: "

Invoice #1234

Total: $99.00

", format: "A4", printBackground: true, margins: { top: "1cm", right: "1cm", bottom: "1cm", left: "1cm" }, }); ``` -------------------------------- ### Error Handling Source: https://docs.presa.dev/sdks/nodejs Provides guidance on handling potential errors during PDF generation, including `ApiError`, `AuthenticationError`, and `TimeoutError`, with examples of how to catch and inspect these errors. ```APIDOC ## Error handling ```typescript import { PDF, ApiError, AuthenticationError, TimeoutError } from "presa-sdk"; const html = "

Hello

"; try { const result = await PDF.generate({ html }); } catch (err) { if (err instanceof AuthenticationError) { // Missing or invalid API key } else if (err instanceof ApiError) { console.log(err.code); // e.g., "QUOTA_EXCEEDED" console.log(err.status); // e.g., 403 console.log(err.message); // human-readable message } else if (err instanceof TimeoutError) { // Request took too long } } ``` ``` -------------------------------- ### GET /invoices/:id Source: https://docs.presa.dev/frameworks/sveltekit Generates a PDF of a specific invoice based on its ID. ```APIDOC ## GET /invoices/:id ### Description This endpoint retrieves invoice data by ID and generates a PDF representation of it. It supports customization of format and margins. ### Method GET ### Endpoint /invoices/:id ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the invoice to retrieve. #### Query Parameters None #### Request Body None ### Request Example (No request body for GET request) ### Response #### Success Response (200) - **buffer** (binary) - The generated PDF file of the invoice. #### Response Example (Binary PDF content) ``` -------------------------------- ### Handle errors during PDF generation Source: https://docs.presa.dev/sdks/nodejs Illustrates how to implement error handling for PDF generation using the Presa SDK. It catches specific errors like `AuthenticationError`, `ApiError`, and `TimeoutError`, providing examples of how to inspect error details. ```typescript import { PDF, ApiError, AuthenticationError, TimeoutError } from "presa-sdk"; const html = "

Hello

"; try { const result = await PDF.generate({ html }); } catch (err) { if (err instanceof AuthenticationError) { // Missing or invalid API key } else if (err instanceof ApiError) { console.log(err.code); // e.g., "QUOTA_EXCEEDED" console.log(err.status); // e.g., 403 console.log(err.message); // human-readable message } else if (err instanceof TimeoutError) { // Request took too long } } ``` -------------------------------- ### GET /api/invoice/{invoice_id}/pdf Source: https://docs.presa.dev/frameworks/fastapi Generates a PDF for a specific invoice, with error handling for API errors and quota exceeded. ```APIDOC ## GET /api/invoice/{invoice_id}/pdf ### Description Generates a PDF for a specific invoice, with error handling for API errors and quota exceeded. ### Method GET ### Endpoint /api/invoice/{invoice_id}/pdf ### Parameters #### Path Parameters - **invoice_id** (str) - Required - The ID of the invoice to generate a PDF for. ### Response #### Success Response (200) - **Content-Disposition** (str) - Attachment header for the PDF file. - **Content-Type** (str) - application/pdf - **Body** (binary) - The generated PDF file. #### Error Response (429) - **detail** (str) - PDF quota exceeded. #### Error Response (500) - **detail** (str) - PDF generation failed. #### Response Example (Binary PDF content) ``` -------------------------------- ### Bearer Token Authentication Header Source: https://docs.presa.dev/api-reference/overview Example of how to include an API key for programmatic access using Bearer Token authentication. This involves setting the 'Authorization' header with your unique API key. ```http Authorization: Bearer your-api-key ``` -------------------------------- ### Set Presa API Key Source: https://docs.presa.dev/guides/puppeteer-migration This command sets the Presa API key as an environment variable. The API key is required for authentication when using the Presa SDK to generate PDFs. ```bash export PRESA_API_KEY=your-api-key ``` -------------------------------- ### Client Instance Source: https://docs.presa.dev/sdks/go Demonstrates how to create a client instance for more control over API requests, including setting API keys, base URLs, and timeouts. ```APIDOC ## Client Instance ### Description Demonstrates how to create a client instance for more control over API requests, including setting API keys, base URLs, and timeouts. ### Method N/A (Function call) ### Endpoint N/A ### Parameters #### Request Body (Config struct for `NewClient`) - **APIKey** (string) - Required/Optional - Your Presa API key. Alternatively, set the `PRESA_API_KEY` environment variable. - **BaseURL** (string) - Optional - The base URL for the Presa API. Defaults to `https://api.presa.dev`. - **Timeout** (time.Duration) - Optional - The timeout for API requests. Defaults to 30 seconds. ### Request Example ```go import ( "context" "log" "time" presa "github.com/faiscadev/presa-go" ) client, err := presa.NewClient(&presa.Config{ APIKey: "your-api-key", // or set PRESA_API_KEY env var BaseURL: "https://api.presa.dev", // default Timeout: 30 * time.Second, // default }) if err != nil { log.Fatal(err) } landscape := true ctx := context.Background() result, err := client.Generate(ctx, presa.Options{ HTML: "

Hello

", Format: "A4", Landscape: &landscape, Margins: &presa.Margins{Top: "1cm", Right: "1cm", Bottom: "1cm", Left: "1cm"}, }) ``` ### Response #### Success Response (200) - **Size** (int) - The size of the generated PDF in bytes. - **Buffer** ([]byte) - The byte buffer containing the PDF content. #### Response Example ```json { "Size": 5432, "Buffer": "...pdf content..." } ``` ``` -------------------------------- ### Create Presa client instance and generate PDF Source: https://docs.presa.dev/sdks/nodejs Shows how to create a `Presa` client instance for more granular control over PDF generation. This includes setting the API key, base URL, and timeout. It also demonstrates generating a PDF with various options like format, orientation, margins, and scale. ```typescript import { Presa } from "presa-sdk"; const client = new Presa({ apiKey: "your-api-key", // or set PRESA_API_KEY env var baseUrl: "https://api.presa.dev", // default timeout: 30000, // ms, default }); const result = await client.generate({ html: "

Hello

", format: "A4", landscape: false, margins: { top: "1cm", right: "1cm", bottom: "1cm", left: "1cm" }, printBackground: true, scale: 1.0, }); ``` -------------------------------- ### Create Presa Client Instance and Generate PDF Source: https://docs.presa.dev/sdks/python Shows how to create a `Presa` client instance with custom configuration, including API key, base URL, and timeout. It then uses this client to generate a PDF with specified options like format, orientation, margins, and background printing. ```python from presa import Presa, PresaConfig, GenerateOptions, Margins client = Presa(PresaConfig( api_key="your-api-key", # or set PRESA_API_KEY env var base_url="https://api.presa.dev", # default timeout=30.0, # seconds, default )) result = client.generate(GenerateOptions( html="

Hello

", format="A4", landscape=False, margins=Margins(top="1cm", right="1cm", bottom="1cm", left="1cm"), print_background=True, scale=1.0, )) ``` -------------------------------- ### Options Source: https://docs.presa.dev/sdks/go Details the available options for the `presa.Options` struct, which allows customization of the PDF generation process. ```APIDOC ## Options ### Description Details the available options for the `presa.Options` struct, which allows customization of the PDF generation process. ### Method N/A (Struct definition) ### Endpoint N/A ### Parameters #### Request Body (Options struct) - **HTML** (string) - Required - The HTML content to convert to PDF. - **Format** (any) - Optional - The page format. Accepts predefined values like `"A4"`, `"Letter"`, `"Legal"`, or a custom `CustomFormat{}`. Defaults to `"A4"`. - **Landscape** (*bool) - Optional - Specifies landscape orientation. Defaults to `false`. - **Margins** (*Margins) - Optional - Defines page margins using CSS units (e.g., `"1cm"`). Defaults to `1cm` on all sides. - **PrintBackground** (*bool) - Optional - Determines whether to print background graphics. Defaults to `true`. - **Scale** (*float64) - Optional - Adjusts the content scale, with a range from 0.1 to 2.0. Defaults to `1.0`. ### Request Example ```go // Example usage within client.Generate or presa.Generate presa.Options{ HTML: "

My Document

", Format: "Letter", Landscape: func() *bool { b := true; return &b }(), Margins: &presa.Margins{Top: "0.5in", Bottom: "0.5in"}, PrintBackground: func() *bool { b := false; return &b }(), Scale: func() *float64 { f := 1.5; return &f }(), } ``` ### Response N/A (This section describes input options, not direct responses.) ``` -------------------------------- ### Async PDF Generation Source: https://docs.presa.dev/frameworks/fastapi Demonstrates how to asynchronously generate a PDF using FastAPI and asyncio. ```APIDOC ## POST /api/pdf (Async) ### Description Asynchronously generates a PDF document from provided HTML content using FastAPI and asyncio. ### Method POST ### Endpoint /api/pdf ### Parameters #### Request Body - **html** (str) - Required - The HTML content to convert to PDF. ### Request Example ```json { "html": "

Async PDF

" } ``` ### Response #### Success Response (200) - **Content-Type** (str) - application/pdf - **Body** (binary) - The generated PDF file. #### Response Example (Binary PDF content) ``` -------------------------------- ### Options for PDF Generation Source: https://docs.presa.dev/sdks/nodejs Details the available options for the `generate` method, including `html`, `format`, `landscape`, `margins`, `printBackground`, and `scale`, along with their types, default values, and descriptions. ```APIDOC ## Options Option| Type| Default| Description ---|---|---|--- `html`| `string`| _required_| HTML content to convert `format`| `"A4" | "Letter" | "Legal" | { width, height }`| `"A4"`| Paper format `landscape`| `boolean`| `false`| Landscape orientation `margins`| `{ top?, right?, bottom?, left? }`| `"1cm"` all| Page margins (CSS units) `printBackground`| `boolean`| `true`| Print background graphics `scale`| `number`| `1.0`| Content scale (0.1–2.0) ``` -------------------------------- ### POST /generate-pdf Source: https://docs.presa.dev/frameworks/sveltekit Generates a PDF document from provided HTML content. ```APIDOC ## POST /generate-pdf ### Description This endpoint accepts an HTML string in the request body and returns a PDF document. ### Method POST ### Endpoint /generate-pdf ### Parameters #### Query Parameters None #### Request Body - **html** (string) - Required - The HTML content to convert to PDF. ### Request Example ```json { "html": "

Hello World

This is a PDF generated from HTML.

" } ``` ### Response #### Success Response (200) - **buffer** (binary) - The generated PDF file. #### Response Example (Binary PDF content) ``` -------------------------------- ### POST /api/pdf Source: https://docs.presa.dev/frameworks/fastapi Generates a PDF document from provided HTML content. ```APIDOC ## POST /api/pdf ### Description Generates a PDF document from provided HTML content. ### Method POST ### Endpoint /api/pdf ### Parameters #### Request Body - **html** (str) - Required - The HTML content to convert to PDF. ### Request Example ```json { "html": "

Hello World

" } ``` ### Response #### Success Response (200) - **Content-Disposition** (str) - Attachment header for the PDF file. - **Content-Type** (str) - application/pdf - **Body** (binary) - The generated PDF file. #### Response Example (Binary PDF content) ``` -------------------------------- ### Async PDF Generation Endpoint (FastAPI) Source: https://docs.presa.dev/frameworks/fastapi Demonstrates how to use the Presa SDK asynchronously within a FastAPI application. It utilizes `asyncio.to_thread` to run the synchronous Presa PDF generation in a separate thread, preventing blocking of the event loop. ```python import asyncio from fastapi import FastAPI from fastapi.responses import Response from pydantic import BaseModel from presa import PDF app = FastAPI() class PdfRequest(BaseModel): html: str @app.post("/api/pdf") async def generate_pdf_async(req: PdfRequest) -> Response: result = await asyncio.to_thread(PDF.generate, html=req.html) return Response(content=result.buffer, media_type="application/pdf") ``` -------------------------------- ### Generate PDF from React Template using Route Handler Source: https://docs.presa.dev/frameworks/nextjs Shows how to use a Next.js Route Handler to generate a PDF by rendering a React component to HTML. It fetches invoice data, renders the template, and returns the PDF. ```typescript import { PDF } from "presa-sdk"; import { renderToString } from "react-dom/server"; import { InvoiceTemplate } from "@/components/invoice-template"; export async function GET( _request: Request, { params }: { params: { id: string } }, ) { const invoice = await getInvoice(params.id); const html = renderToString(); const { buffer } = await PDF.generate({ html }); return new Response(buffer, { headers: { "Content-Type": "application/pdf" }, }); } ``` -------------------------------- ### SvelteKit Server Load Function for Dynamic PDF Generation Source: https://docs.presa.dev/frameworks/sveltekit A SvelteKit server load function that fetches invoice data and generates a PDF dynamically. It constructs HTML from the invoice data and uses the Presa SDK with specified formatting and margins. ```typescript import { PDF } from "presa-sdk"; import type { RequestHandler } from "./$types"; export const GET: RequestHandler = async ({ params }) => { const invoice = await getInvoice(params.id); const html = `

Invoice #${invoice.id}

Total: $${invoice.total}

`; const { buffer } = await PDF.generate({ html, format: "A4", margins: { top: "2cm", bottom: "2cm", left: "1.5cm", right: "1.5cm" }, }); return new Response(buffer, { headers: { "Content-Type": "application/pdf" }, }); }; ``` -------------------------------- ### PDF Generation with Advanced Error Handling in Gin Source: https://docs.presa.dev/frameworks/gin An advanced Gin handler for generating PDFs with specific error handling for Presa API errors, such as quota exceeded. It fetches invoice data, renders HTML, generates the PDF, and handles potential errors gracefully. Requires the Presa Go SDK and Gin. ```go import ( "errors" "fmt" "net/http" "github.com/gin-gonic/gin" presa "github.com/faiscadev/presa-go" ) r.GET("/api/invoice/:id/pdf", func(c *gin.Context) { invoice, err := getInvoice(c.Param("id")) if err != nil { c.JSON(http.StatusNotFound, gin.H{"error": "Invoice not found"}) return } html := renderInvoice(invoice) result, err := client.Generate(c.Request.Context(), presa.Options{ HTML: html, }) if err != nil { var apiErr *presa.APIError if errors.As(err, &apiErr) && apiErr.Code == "QUOTA_EXCEEDED" { c.JSON(http.StatusTooManyRequests, gin.H{"error": "PDF quota exceeded"}) return } c.JSON(http.StatusInternalServerError, gin.H{"error": "PDF generation failed"}) return } filename := fmt.Sprintf("invoice-%s.pdf", invoice.ID) c.Header("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, filename)) c.Data(http.StatusOK, "application/pdf", result.Buffer) }) ``` -------------------------------- ### Error Handling Source: https://docs.presa.dev/sdks/go Illustrates how to handle various types of errors that may occur during PDF generation, including authentication, API, and timeout errors. ```APIDOC ## Error Handling ### Description Illustrates how to handle various types of errors that may occur during PDF generation, including authentication, API, and timeout errors. ### Method N/A (Error handling logic) ### Endpoint N/A ### Parameters N/A ### Request Example ```go import ( "errors" "fmt" presa "github.com/faiscadev/presa-go" ) result, err := presa.Generate(context.Background(), presa.Options{HTML: html}) if err != nil { var authErr *presa.AuthenticationError var apiErr *presa.APIError var timeoutErr *presa.TimeoutError switch { case errors.As(err, &authErr): // Handle authentication error (e.g., Missing or invalid API key) fmt.Println("Authentication Error") case errors.As(err, &apiErr): // Handle API error fmt.Println(apiErr.Code) // e.g., "QUOTA_EXCEEDED" fmt.Println(apiErr.Status) // e.g., 403 fmt.Println(apiErr.Message) // human-readable error message case errors.As(err, &timeoutErr): // Handle timeout error fmt.Println("Request timed out") default: // Handle other errors (e.g., network issues) fmt.Println("An unexpected error occurred") } } ``` ### Response #### Error Responses - **AuthenticationError**: Occurs due to missing or invalid API keys. - **APIError**: Represents errors returned by the Presa API, with fields for `Code`, `Status`, and `Message`. - **TimeoutError**: Indicates that the request exceeded the configured timeout. - **Other Errors**: Includes network issues or other unexpected problems. ``` -------------------------------- ### Basic PDF Generation Endpoint (FastAPI) Source: https://docs.presa.dev/frameworks/fastapi A basic FastAPI endpoint that accepts HTML content and uses the Presa SDK to generate a PDF. It returns the generated PDF as a response with appropriate headers. ```python from fastapi import FastAPI from fastapi.responses import Response from pydantic import BaseModel from presa import PDF app = FastAPI() class PdfRequest(BaseModel): html: str @app.post("/api/pdf") def generate_pdf(req: PdfRequest) -> Response: result = PDF.generate(html=req.html) return Response( content=result.buffer, media_type="application/pdf", headers={"Content-Disposition": 'attachment; filename="document.pdf"'}, ) ``` -------------------------------- ### Import TypeScript types for Presa SDK Source: https://docs.presa.dev/sdks/nodejs Shows how to import various TypeScript types from the Presa SDK, such as `GenerateOptions`, `GenerateResult`, `PresaConfig`, `Margins`, and `PageFormat`. These types enhance code completion and type safety in TypeScript projects. ```typescript import type { GenerateOptions, GenerateResult, PresaConfig, Margins, PageFormat, } from "presa-sdk"; ``` -------------------------------- ### Import Type Hinting Definitions from Presa SDK Source: https://docs.presa.dev/sdks/python Imports type hinting definitions from the Presa SDK, enabling static type checking with tools like mypy and pyright. This ensures better code quality and maintainability. ```python from presa import GenerateOptions, GenerateResult, PresaConfig, Margins ``` -------------------------------- ### Generate PDF using Server Action Source: https://docs.presa.dev/frameworks/nextjs Implements a Next.js Server Action to generate a PDF from invoice data. This action fetches invoice details and returns the PDF content as a base64 encoded string. ```typescript "use server"; import { PDF } from "presa-sdk"; export async function generateInvoicePDF(invoiceId: string) { const invoice = await getInvoice(invoiceId); const html = `

Invoice #${invoice.id}

Total: $${invoice.total}

`; const { buffer } = await PDF.generate({ html }); return Buffer.from(buffer).toString("base64"); } ``` -------------------------------- ### Basic PDF Generation Route with Express Source: https://docs.presa.dev/frameworks/express Creates a basic Express.js POST route to generate a PDF from HTML provided in the request body. It uses the Presa SDK's PDF.generate method and handles potential errors. ```javascript import express from "express"; import { PDF } from "presa-sdk"; const app = express(); app.use(express.json()); app.post("/api/pdf", async (req, res) => { try { const { buffer } = await PDF.generate({ html: req.body.html }); res.set("Content-Type", "application/pdf"); res.send(Buffer.from(buffer)); } catch (err) { res.status(500).json({ error: "PDF generation failed" }); } }); app.listen(3000); ``` -------------------------------- ### API Overview Source: https://docs.presa.dev/api-reference/overview General information about the Presa API, including the OpenAPI specification and base URL. ```APIDOC ## API Overview ### OpenAPI Specification The full OpenAPI 3.1 specification is available at `docs.presa.dev/openapi.yaml`. This can be imported into tools like Postman or Insomnia. ### Base URL The base URL for all API requests is: `https://api.presa.dev` ``` -------------------------------- ### SvelteKit Server Endpoint for PDF Generation Source: https://docs.presa.dev/frameworks/sveltekit A SvelteKit server endpoint that accepts HTML content via a POST request and generates a PDF. It utilizes the Presa SDK's `generate` function and returns the PDF as a response. ```typescript import { PDF } from "presa-sdk"; import type { RequestHandler } from "./$types"; export const POST: RequestHandler = async ({ request }) => { const { html } = await request.json(); const { buffer } = await PDF.generate({ html }); return new Response(buffer, { headers: { "Content-Type": "application/pdf", "Content-Disposition": 'attachment; filename="document.pdf"', }, }); }; ``` -------------------------------- ### Generate PDF from HTML using App Router API Route Source: https://docs.presa.dev/frameworks/nextjs Demonstrates how to create an API route in Next.js App Router to generate a PDF from provided HTML content. It expects JSON with an 'html' field and returns a PDF buffer. ```typescript import { PDF } from "presa-sdk"; export async function POST(request: Request) { const { html } = await request.json(); const { buffer } = await PDF.generate({ html }); return new Response(buffer, { headers: { "Content-Type": "application/pdf", "Content-Disposition": 'attachment; filename="invoice.pdf"', }, }); } ```