Vue.js
This guide explains how to generate an HTML string using Vue.js's server-side rendering and convert it to PDF by sending it to pdfg's API.
Technical Overview
- Create Vue.js components
- Use @vue/server-renderer to convert to HTML string
- Send the generated HTML string to pdfg's API to convert it to PDF
Sample
Defining the Component
<!-- Invoice.vue -->
<template>
<html>
<head></head>
<body>
<div class="invoice">
<h1>Invoice</h1>
<table>
<thead>
<tr>
<th>Item</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in items" :key="index">
<td>{{ item.name }}</td>
<td>{{ item.price }} USD</td>
</tr>
</tbody>
</table>
<p class="total">Total: {{ total }} USD</p>
</div>
</body>
</html>
</template>
<script lang="ts">
import { defineComponent, PropType } from "vue";
interface Item {
name: string;
price: number;
}
export default defineComponent({
props: {
items: {
type: Array as PropType<Item[]>,
required: true,
},
total: {
type: Number,
required: true,
},
},
});
</script>
Using the Component and Generating PDF
// generatePdf.ts
import { createSSRApp } from "vue";
import { renderToString } from "@vue/server-renderer";
import Invoice from "./Invoice.vue";
import fs from "fs";
// Prepare data
const items = [
{ name: "Product A", price: 1000 },
{ name: "Product B", price: 2000 },
];
// Create Vue application
const app = createSSRApp(Invoice, {
items,
total: 3000,
});
// Convert to HTML string
const html = await renderToString(app);
// Request to pdfg's API
const response = await fetch("https://api.pdfg.net/v1", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer YOUR_API_KEY",
},
body: JSON.stringify({
html: html,
pdfOptions: {
format: "A4",
},
}),
});
// Save PDF
if (response.ok) {
const pdfBuffer = await response.arrayBuffer();
fs.writeFileSync("invoice.pdf", Buffer.from(pdfBuffer));
}