;
async function getLLMResult(env, prompt: string, schema?: any) {
const model = "@hf/thebloke/deepseek-coder-6.7b-instruct-awq"
const requestBody = {
messages: [{
role: "user",
content: prompt
}],
};
const aiUrl = `https://api.cloudflare.com/client/v4/accounts/${env.ACCOUNT_ID}/ai/run/${model}`
const response = await fetch(aiUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${env.API_TOKEN}`,
},
body: JSON.stringify(requestBody),
});
if (!response.ok) {
console.log(JSON.stringify(await response.text(), null, 2));
throw new Error(`LLM call failed ${aiUrl} ${response.status}`);
}
// process response
const data = await response.json() as { result: { response: string }};
const text = data.result.response || '';
const value = (text.match(/```(?:json)?\s*([\s\S]*?)\s*```/) || [null, text])[1];
try {
return JSON.parse(value);
} catch(e) {
console.error(`${e} . Response: ${value}`)
}
}
```
You can run this script to test it using Wrangler's `--remote` flag:
```sh
npx wrangler dev --remote
```
With your script now running, you can go to `http://localhost:8787/` and should see something like the following:
```json
{
"title": "IP Addresses in 2024",
"url": "http://example.com/ip-addresses-in-2024",
"date": "11 Jan 2025"
}
```
For more complex websites or prompts, you might need a better model. Check out the latest models in [Workers AI](/workers-ai/models/).
---
# Generate PDFs Using HTML and CSS
URL: https://developers.cloudflare.com/browser-rendering/how-to/pdf-generation/
import { Aside, WranglerConfig, PackageManagers } from "~/components";
As seen in the [Getting Started guide](/browser-rendering/workers-binding-api/screenshots/), Browser Rendering can be used to generate screenshots for any given URL. Alongside screenshots, you can also generate full PDF documents for a given webpage, and can also provide the webpage markup and style ourselves.
## Prerequisites
1. Use the `create-cloudflare` CLI to generate a new Hello World Cloudflare Worker script:
2. Install `@cloudflare/puppeteer`, which allows you to control the Browser Rendering instance:
3. Add your Browser Rendering binding to your new Wrangler configuration:
```toml title="wrangler.toml"
browser = { binding = "BROWSER" }
```
4. Replace the contents of `src/index.ts` (or `src/index.js` for JavaScript projects) with the following skeleton script:
```ts
import puppeteer from "@cloudflare/puppeteer";
const generateDocument = (name: string) => {};
export default {
async fetch(request, env) {
const { searchParams } = new URL(request.url);
let name = searchParams.get("name");
if (!name) {
return new Response("Please provide a name using the ?name= parameter");
}
const browser = await puppeteer.launch(env.BROWSER);
const page = await browser.newPage();
// Step 1: Define HTML and CSS
const document = generateDocument(name);
// Step 2: Send HTML and CSS to our browser
await page.setContent(document);
// Step 3: Generate and return PDF
return new Response();
},
};
```
## 1. Define HTML and CSS
Rather than using Browser Rendering to navigate to a user-provided URL, manually generate a webpage, then provide that webpage to the Browser Rendering instance. This allows you to render any design you want.
:::note
You can generate your HTML or CSS using any method you like. This example uses string interpolation, but the method is also fully compatible with web frameworks capable of rendering HTML on Workers such as React, Remix, and Vue.
:::
For this example, we are going to take in user-provided content (via a '?name=' parameter), and have that name output in the final PDF document.
To start, fill out your `generateDocument` function with the following:
```ts
const generateDocument = (name: string) => {
return `
This is to certify that
${name}
has rendered a PDF using Cloudflare Workers
`;
};
```
This example HTML document should render a beige background imitating a certificate showing that the user-provided name has successfully rendered a PDF using Cloudflare Workers.
:::note
It is usually best to avoid directly interpolating user-provided content into an image or PDF renderer in production applications. To render contents like an invoice, it would be best to validate the data input and fetch the data yourself using tools like [D1](/d1/) or [Workers KV](/kv/).
:::
## 2. Load HTML and CSS Into Browser
Now that you have your fully styled HTML document, you can take the contents and send it to your browser instance. Create an empty page to store this document as follows:
```ts
const browser = await puppeteer.launch(env.BROWSER);
const page = await browser.newPage();
```
The [`page.setContent()`](https://github.com/cloudflare/puppeteer/blob/main/docs/api/puppeteer.page.setcontent.md) function can then be used to set the page's HTML contents from a string, so you can pass in your created document directly like so:
```ts
await page.setContent(document);
```
## 3. Generate and Return PDF
With your Browser Rendering instance now rendering your provided HTML and CSS, you can use the [`page.pdf()`](https://github.com/cloudflare/puppeteer/blob/main/docs/api/puppeteer.page.pdf.md) command to generate a PDF file and return it to the client.
```ts
let pdf = page.pdf({ printBackground: true });
```
The `page.pdf()` call supports a [number of options](https://github.com/cloudflare/puppeteer/blob/main/docs/api/puppeteer.pdfoptions.md), including setting the dimensions of the generated PDF to a specific paper size, setting specific margins, and allowing fully-transparent backgrounds. For now, you are only overriding the `printBackground` option to allow your `body` background styles to show up.
Now that you have your PDF data, return it to the client in the `Response` with an `application/pdf` content type:
```ts
return new Response(pdf, {
headers: {
"content-type": "application/pdf",
},
});
```
## Conclusion
The full Worker script now looks as follows:
```ts
import puppeteer from "@cloudflare/puppeteer";
const generateDocument = (name: string) => {
return `
This is to certify that
${name}
has rendered a PDF using Cloudflare Workers
`;
};
export default {
async fetch(request, env) {
const { searchParams } = new URL(request.url);
let name = searchParams.get("name");
if (!name) {
return new Response("Please provide a name using the ?name= parameter");
}
const browser = await puppeteer.launch(env.BROWSER);
const page = await browser.newPage();
// Step 1: Define HTML and CSS
const document = generateDocument(name);
// // Step 2: Send HTML and CSS to our browser
await page.setContent(document);
// // Step 3: Generate and return PDF
const pdf = await page.pdf({ printBackground: true });
// Close browser since we no longer need it
await browser.close();
return new Response(pdf, {
headers: {
"content-type": "application/pdf",
},
});
},
};
```
You can run this script to test it using Wrangler’s `--remote` flag:
With your script now running, you can pass in a `?name` parameter to the local URL (such as `http://localhost:8787/?name=Harley`) and should see the following:
.
---
Dynamically generating PDF documents solves a number of common use-cases, from invoicing customers to archiving documents to creating dynamic certificates (as seen in the simple example here).
---