Q: How I can create a PDF from just text?
A: An input text can be used to generate a Word Document, which then can be converted by PDFTron to a PDF and displayed in the WebViewer. The following is a HTML/Javascript example that can be run entirely in the browser:
<!-- index.html -->
<!DOCTYPE html>
<html style="height: 100%;">
<head>
<meta http-equiv="Content-Type" content="text/html" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<!-- "docx" is a module used to generate a .docx documents.-->
<script src="https://unpkg.com/docx@5.0.2/build/index.js"></script>
<!-- PDFTron's CoreControl is used to convert .docx to PDF and
WebViewer to display the PDF. -->
<script src="../../../lib/core/CoreControls.js"></script>
<script src="../../../lib/webviewer.min.js"></script>
</head>
<body style="width: 100%; height: 100%; margin: 0px; padding: 0px; overflow: hidden;">
<div id="viewer" style="height: 100%; overflow: hidden;"></div>
<script>
var viewerElement = document.getElementById("viewer");
WebViewer(
{
type: "html5",
path: "../../../lib",
documentType: "pdf",
showLocalFilePicker: true,
enableAnnotations: true,
fullAPI: true,
},
viewerElement
).then(async (instance) => {
// Generate a new Word document from scratch
const doc = new docx.Document();
doc.addSection({
properties: {},
children: [
new docx.Paragraph({
children: [new docx.TextRun("PDFTron Word Sample")],
}),
new docx.Paragraph({
children: [su
new docx.TextRun({
text: "This .docx document was generated from scratch within this sample using the 'docx' npm module and then converted and loaded with PDFTron.",
bold: true,
}),
],
}),
],
});
// Transform the document into a Word buffer
const buffer = await docx.Packer.toBuffer(doc);
// Convert the Word buffer into PDF buffer
const options = {
extension: "docx",
};
CoreControls.setWorkerPath("../../../lib/core");
await PDFNet.initialize();
const buf = await CoreControls.office2PDFBuffer(buffer, options);
// Convert the PDF buffer into a PDF
const blobPDF = new Blob([buf], { type: "application/pdf" });
// Load PDF into WebViewer
instance.loadDocument(blobPDF);
});
</script>
</body>
</html>