> ## Documentation Index
> Fetch the complete documentation index at: https://docs.iyzpdf.com/llms.txt
> Use this file to discover all available pages before exploring further.

# HTML To PDF

> Render inline HTML, uploaded HTML files, or public URLs into PDF.

## Notes

* Credits: `1` for inline HTML or file upload, `2` for URL mode
* Use either `html` or `url`, never both
* URL mode only supports public `http` and `https` addresses
* Private or internal URLs are rejected
* Authenticated HTML payloads and HTML uploads are limited to `10 MB`


## OpenAPI

````yaml /openapi.json post /convert/html-to-pdf
openapi: 3.0.3
info:
  title: IyzPdf Client API
  version: 1.0.0
  description: Client-facing document conversion and PDF editing endpoints for IyzPdf.
servers:
  - url: https://api.iyzpdf.com/v1
security:
  - ApiKeyAuth: []
tags:
  - name: Conversion
  - name: PDF Editing
paths:
  /convert/html-to-pdf:
    post:
      tags:
        - Conversion
      summary: Convert HTML, an uploaded HTML file, or a public URL into PDF
      description: >-
        Supports JSON requests for inline HTML or URL mode, and multipart
        requests for uploaded HTML files. Use X-API-Key on every request shown
        in this documentation.
      operationId: htmlToPdf
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/HtmlToPdfRequest'
            examples:
              inlineHtml:
                summary: Inline HTML
                value:
                  html: >-
                    <!doctype html><html><body><h1>Invoice #1042</h1><p>Total:
                    $99.00</p></body></html>
                  options:
                    format: A4
                    marginTop: 2cm
                    marginBottom: 2cm
                    printBackground: true
              publicUrl:
                summary: Public URL
                value:
                  url: https://example.com/invoices/1042
                  options:
                    format: A4
                    waitForSelector: body
                    waitTimeout: 15000
          multipart/form-data:
            schema:
              type: object
              properties:
                file:
                  type: string
                  format: binary
                  description: Uploaded HTML file.
                options:
                  type: string
                  description: JSON-encoded PdfOptions object.
              required:
                - file
            examples:
              htmlFile:
                summary: HTML file upload
                value:
                  file: (binary)
                  options: >-
                    {"format":"A4","marginTop":"2cm","marginBottom":"2cm","printBackground":true}
      responses:
        '200':
          description: >-
            Successful response. Send Accept: application/json to receive file
            metadata instead of the binary payload.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BinaryFileMetadataResponse'
              example:
                fileName: output.pdf
                size: 183240
                creditsUsed: 1
                creditsRemaining: 49
                contentType: application/pdf
            application/pdf:
              schema:
                type: string
                format: binary
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '402':
          $ref: '#/components/responses/PaymentRequired'
        '403':
          $ref: '#/components/responses/Forbidden'
        '413':
          $ref: '#/components/responses/PayloadTooLarge'
        '415':
          $ref: '#/components/responses/UnsupportedMediaType'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/InternalError'
      x-codeSamples:
        - label: curl
          lang: bash
          source: |-
            curl --request POST \
              --url https://api.iyzpdf.com/v1/convert/html-to-pdf \
              --header "X-API-Key: $IYZPDF_API_KEY" \
              --header "Content-Type: application/json" \
              --data '{
                "html": "<!doctype html><html><body><h1>Invoice #1042</h1><p>Total: $99.00</p></body></html>",
                "options": {
                  "format": "A4",
                  "marginTop": "2cm",
                  "marginBottom": "2cm",
                  "printBackground": true
                }
              }' \
              --output invoice.pdf
        - label: python
          lang: python
          source: |-
            import os
            import requests

            api_key = os.environ["IYZPDF_API_KEY"]
            payload = {
                "html": "<!doctype html><html><body><h1>Invoice #1042</h1><p>Total: $99.00</p></body></html>",
                "options": {
                    "format": "A4",
                    "marginTop": "2cm",
                    "marginBottom": "2cm",
                    "printBackground": True,
                },
            }

            response = requests.post(
                "https://api.iyzpdf.com/v1/convert/html-to-pdf",
                headers={"X-API-Key": api_key},
                json=payload,
                timeout=60,
            )

            if not response.ok:
                raise Exception(response.text)

            with open("invoice.pdf", "wb") as output_file:
                output_file.write(response.content)
        - label: javascript
          lang: javascript
          source: >-
            import { writeFile } from "node:fs/promises";


            const apiKey = process.env.IYZPDF_API_KEY;


            const payload = {
              html: "<!doctype html><html><body><h1>Invoice #1042</h1><p>Total: $99.00</p></body></html>",
              options: {
                format: "A4",
                marginTop: "2cm",
                marginBottom: "2cm",
                printBackground: true
              }
            };


            const response = await
            fetch("https://api.iyzpdf.com/v1/convert/html-to-pdf", {
              method: "POST",
              headers: {
                "X-API-Key": apiKey,
                "Content-Type": "application/json"
              },
              body: JSON.stringify(payload)
            });


            if (!response.ok) {
              throw new Error(await response.text());
            }


            const fileBuffer = Buffer.from(await response.arrayBuffer());

            await writeFile("invoice.pdf", fileBuffer);
        - label: php
          lang: php
          source: |-
            <?php

            $apiKey = getenv('IYZPDF_API_KEY');

            $payload = [
                'html' => '<!doctype html><html><body><h1>Invoice #1042</h1><p>Total: $99.00</p></body></html>',
                'options' => [
                    'format' => 'A4',
                    'marginTop' => '2cm',
                    'marginBottom' => '2cm',
                    'printBackground' => true,
                ],
            ];

            $ch = curl_init('https://api.iyzpdf.com/v1/convert/html-to-pdf');

            curl_setopt_array($ch, [
                CURLOPT_POST => true,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_HTTPHEADER => [
                    'X-API-Key: ' . $apiKey,
                    'Content-Type: application/json',
                ],
                CURLOPT_POSTFIELDS => json_encode($payload),
            ]);

            $pdf = curl_exec($ch);
            $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

            if ($pdf === false || $status !== 200) {
                throw new RuntimeException('Request failed: ' . curl_error($ch) . PHP_EOL . $pdf);
            }

            file_put_contents('invoice.pdf', $pdf);
            curl_close($ch);
        - label: java
          lang: java
          source: |-
            import java.net.URI;
            import java.net.http.HttpClient;
            import java.net.http.HttpRequest;
            import java.net.http.HttpResponse;
            import java.nio.file.Files;
            import java.nio.file.Path;

            public class HtmlToPdfExample {
                public static void main(String[] args) throws Exception {
                    String apiKey = System.getenv("IYZPDF_API_KEY");
                    HttpClient client = HttpClient.newHttpClient();

                    String json = """
                        {
                          "html": "<!doctype html><html><body><h1>Invoice #1042</h1><p>Total: $99.00</p></body></html>",
                          "options": {
                            "format": "A4",
                            "marginTop": "2cm",
                            "marginBottom": "2cm",
                            "printBackground": true
                          }
                        }
                        """;

                    HttpRequest request = HttpRequest.newBuilder()
                        .uri(URI.create("https://api.iyzpdf.com/v1/convert/html-to-pdf"))
                        .header("X-API-Key", apiKey)
                        .header("Content-Type", "application/json")
                        .POST(HttpRequest.BodyPublishers.ofString(json))
                        .build();

                    HttpResponse<byte[]> response = client.send(request, HttpResponse.BodyHandlers.ofByteArray());

                    if (response.statusCode() != 200) {
                        throw new RuntimeException("Request failed with status " + response.statusCode());
                    }

                    Files.write(Path.of("invoice.pdf"), response.body());
                }
            }
        - label: c#
          lang: csharp
          source: |-
            using System.Net.Http.Json;

            var apiKey = Environment.GetEnvironmentVariable("IYZPDF_API_KEY");
            using var client = new HttpClient();

            client.DefaultRequestHeaders.Add("X-API-Key", apiKey);

            var payload = new
            {
                html = "<!doctype html><html><body><h1>Invoice #1042</h1><p>Total: $99.00</p></body></html>",
                options = new
                {
                    format = "A4",
                    marginTop = "2cm",
                    marginBottom = "2cm",
                    printBackground = true
                }
            };

            using var response = await client.PostAsJsonAsync(
                "https://api.iyzpdf.com/v1/convert/html-to-pdf",
                payload);

            response.EnsureSuccessStatusCode();

            await using var output = File.Create("invoice.pdf");
            await response.Content.CopyToAsync(output);
components:
  schemas:
    HtmlToPdfRequest:
      type: object
      properties:
        html:
          type: string
          nullable: true
        url:
          type: string
          format: uri
          nullable: true
        options:
          $ref: '#/components/schemas/PdfOptions'
      example:
        html: >-
          <!doctype html><html><body><h1>Invoice #1042</h1><p>Total:
          $99.00</p></body></html>
        options:
          format: A4
          marginTop: 2cm
          marginBottom: 2cm
          printBackground: true
    BinaryFileMetadataResponse:
      type: object
      properties:
        fileName:
          type: string
        size:
          type: integer
          format: int32
        creditsUsed:
          type: integer
          format: int32
        creditsRemaining:
          type: integer
          format: int32
          nullable: true
        contentType:
          type: string
      required:
        - fileName
        - size
        - creditsUsed
        - contentType
      example:
        fileName: output.pdf
        size: 183240
        creditsUsed: 1
        creditsRemaining: 49
        contentType: application/pdf
    PdfOptions:
      type: object
      properties:
        format:
          type: string
          default: A4
        landscape:
          type: boolean
          default: false
        marginTop:
          type: string
          default: 1cm
        marginBottom:
          type: string
          default: 1cm
        marginLeft:
          type: string
          default: 1cm
        marginRight:
          type: string
          default: 1cm
        printBackground:
          type: boolean
          default: true
        scale:
          type: number
          format: double
          default: 1
        waitForSelector:
          type: string
          nullable: true
        waitTimeout:
          type: integer
          format: int32
          default: 10000
      example:
        format: A4
        marginTop: 2cm
        marginBottom: 2cm
        printBackground: true
    ErrorResponse:
      type: object
      properties:
        error:
          type: object
          properties:
            code:
              type: string
            message:
              type: string
            creditsRequired:
              type: integer
              format: int32
              nullable: true
            creditsBalance:
              type: integer
              format: int32
              nullable: true
            purchaseUrl:
              type: string
              nullable: true
          required:
            - code
            - message
      required:
        - error
      example:
        error:
          code: INVALID_REQUEST
          message: The request payload is invalid or incomplete.
  responses:
    BadRequest:
      description: Validation error
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            error:
              code: INVALID_REQUEST
              message: The request payload is invalid or incomplete.
    Unauthorized:
      description: Missing or invalid API key
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            error:
              code: UNAUTHORIZED
              message: Missing or invalid API key.
    PaymentRequired:
      description: Insufficient credits
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            error:
              code: INSUFFICIENT_CREDITS
              message: You need more credits to complete this request.
              creditsRequired: 2
              creditsBalance: 0
              purchaseUrl: https://iyzpdf.com/portal/credits
    Forbidden:
      description: Forbidden
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            error:
              code: SSRF_BLOCKED
              message: Private or internal URLs are not allowed.
    PayloadTooLarge:
      description: Payload too large
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            error:
              code: FILE_TOO_LARGE
              message: >-
                The uploaded file or request body exceeds the allowed size
                limit.
    UnsupportedMediaType:
      description: Unsupported media type
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            error:
              code: UNSUPPORTED_MEDIA_TYPE
              message: The uploaded file type or content type is not supported.
    RateLimited:
      description: Rate limit exceeded
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            error:
              code: RATE_LIMIT_EXCEEDED
              message: Too many requests. Please retry after the rate limit resets.
    InternalError:
      description: Processing failed
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            error:
              code: PROCESSING_FAILED
              message: The document could not be processed.
  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: X-API-Key
      description: Send your server-side API key in the X-API-Key header.

````