Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <html>
  <head>
    <title>PDF Generator API Example</title>
  </head>
  <body class="p-2">
    <div class="flex flex-row">
      <div style="width: 25%;">
        <h2 class="p-1 text-lg font-bold border-b border-gray-100">API Credentials</h2>
            <p class="p-2">
      Create a free Sandbox account to get your API credentials at <a href="https://pdfgeneratorapi.com" targer="_blank">pdfgeneratorapi.com</a>. Fill form values and click "Generate PDF" to generate PDF and load it using pdfjs.
    </p>
        <form class="m-4">
          <div class="space-y-4">
          <div>
            <label for="api-key" class="block font-medium">API Key</label>
            <input type="text" name="api_key" id="api-key" class="block rounded ring-1 ring-inset ring-gray-300 p-1" placeholder="Paste your API Key">
          </div>
          <div>
            <label for="api-secret" class="block font-medium">API Secret</label>
            <input type="password" name="api_secret" id="api-secret" class="block rounded ring-1 ring-inset ring-gray-300 p-1" placeholder="Paste your API Secret">
          </div>
            <div>
            <label for="api-workspace" class="block font-medium">Workspace Identifier</label>
            <input type="text" name="api_workspace" id="api-workspace" class="block rounded ring-1 ring-inset ring-gray-300 p-1" placeholder="Paste your Workspace Identifier">
          </div>
            <div>
            <label for="api-templateid" class="block font-medium">Template ID</label>
            <input type="text" name="api_templateid" id="api-templateid" class="block rounded ring-1 ring-inset ring-gray-300 p-1" placeholder="Paste your Template ID">
          </div>
            <div>
            <label for="api-data" class="block font-medium">JSON Data</label>
            <textarea type="text" name="api_data" id="api-data" class="block rounded ring-1 ring-inset ring-gray-300 p-1" placeholder="Paste your JSON that is used to replace values in the template"></textarea>
          </div>
          </div>
          <div class="mt-4">
            <button type="button" id="load-editor-btn" class="rounded-md bg-indigo-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600">Generate PDF</button>
          </div>
        </form>
      </div>
      <div style="width: 75%;">
         <h2 class="p-1 text-lg font-bold border-b border-gray-100">PDF Viewer</h2>
        <p class="p-2">The PDF will appare here.</p> 
        <canvas id="pdf-viewer"></canvas>
      </div>
    </div>
  </body>
</html>
              
            
!

CSS

              
                input, textarea {
  width: 80%;
}

textarea {
  height: 100px;
}
              
            
!

JS

              
                import * as PDFGeneratorAPI from "https://cdn.skypack.dev/pdf-generator-api-client@5.0.1";
import * as jose from "https://cdn.skypack.dev/jose@4.13.1";

const loadEditorBtn = document.querySelector("#load-editor-btn");
const apiKey = document.querySelector("#api-key");
const apiSecret = document.querySelector("#api-secret");
const apiWorkspace = document.querySelector("#api-workspace");
const apiTemplateId = document.querySelector("#api-templateid");
const apiData = document.querySelector("#api-data");

const defaultPDFAPIClient = PDFGeneratorAPI.ApiClient.instance;
let JSONWebTokenAuth = defaultPDFAPIClient.authentications["JSONWebTokenAuth"];

loadEditorBtn.addEventListener("click", (event) => {
  generatePDF(
    apiKey.value,
    apiSecret.value,
    apiWorkspace.value,
    apiTemplateId.value,
    apiData.value ? JSON.parse(apiData.value) : {"test": 1}
  );
});

function generatePDF(apiKey, apiSecret, apiWorkspace, templateId, data) {
  createDocumentsClient(apiKey, apiSecret, apiWorkspace).then((client) => {
    let request = new PDFGeneratorAPI.GenerateDocumentRequest();
    request.template = {
      id: templateId,
      data: data
    };
    request.format = 'pdf';
    request.output = 'url';

    client.generateDocument(request, (error, data, response) => {
      if (error) {
        console.error(error);
      } else {
        const loadingTask = window.pdfjsLib.getDocument(data.response);
        loadingTask.promise.then(function(pdf) {
          pdf.getPage(1).then(function(page) {
            const viewport = page.getViewport({ scale: 1.5, });
            const outputScale = window.devicePixelRatio || 1;
            let canvas = document.getElementById('pdf-viewer');

            canvas.width = Math.floor(viewport.width * outputScale);
            canvas.height = Math.floor(viewport.height * outputScale);
            canvas.style.width = Math.floor(viewport.width) + "px";
            canvas.style.height =  Math.floor(viewport.height) + "px";

            page.render({
              canvasContext: canvas.getContext('2d'),
              transform: outputScale !== 1 ? [outputScale, 0, 0, outputScale, 0, 0] : null,
              viewport: page.getViewport({ scale: 1.5, })
            });
          });
        });
      }
    });
  });
}

async function createDocumentsClient(apiKey, apiSecret, apiWorkspace) {
  JSONWebTokenAuth.accessToken = await createJWT(
    apiKey,
    apiWorkspace,
    apiSecret
  );
  return new PDFGeneratorAPI.DocumentsApi();
}

async function createDocumentClient(apiKey, apiSecret, apiWorkspace) {
  JSONWebTokenAuth.accessToken = await createJWT(
    apiKey,
    apiWorkspace,
    apiSecret
  );
  return new PDFGeneratorAPI.DocumentsApi();
}

async function createJWT(iss, sub, secret) {
  const header = {
    alg: "HS256",
    typ: "JWT"
  };

  const payload = {
    iss: iss,
    sub: sub,
    exp: Math.round(Date.now() / 1000) + 60
  };

  return await new jose.SignJWT(payload)
    .setProtectedHeader(header)
    .sign(new TextEncoder().encode(secret));
}

              
            
!
999px

Console