### 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: "
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="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: "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: "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": "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: "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": "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: "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: "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: "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": "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="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("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: "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 = "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": "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 = `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"', }, }); } ```