HTML to PDF in React Native

PSPDFKit for React Native enables you to convert an HTML string or a URL to a PDF document.

Generating PDF files from a URL is more powerful — but also more time- and memory-intensive — than generating from an HTML string. For best performance, decide which method to use in the following way:

  • If the HTML source is short and simple, generate the PDF document from an HTML string.

  • If the HTML source includes complex structures and a large DOM, generate PDF documents from a URL. If the complex HTML source is stored in a string, first save it to a temporary local file, and then generate the PDF from URL using this file.

License

To convert an HTML string or website to a PDF document, contact Sales to add PDF Generation to your license.

Generating PDF Documents from an HTML String

To generate a PDF document from an HTML string, use the Processor class, which takes a configuration object and an HTML string as its parameters:

const configuration = {
    name: fileName,
    documentPath: `PDFs/${documentName(fileName)}`,
    override: true, // true|false - If `true`, this will override the existing file with the same name.
};
let htmlString = `
<html lang="en">
<head>
<style>
body {
    font-family: sans-serif;
}
</style><title>Demo HTML Document</title>
</head>
<body>
<br/>
<h1>PDF generated from HTML</h1>
<p>Hello HTML</p>
<ul>
    <li>List item 1</li>
    <li>List item 2</li>
    <li>List item 3</li>
</ul>
<p><span style="color: #ff0000;"><strong>&nbsp;Add some style</strong></span></p>
<p>&nbsp;</p>
</body>
</html>`;

    try {
    let { fileURL } = await Processor.generatePDFFromHtmlString(configuration, htmlString);

    // Do something with the new file.
    component.props.navigation.push('GeneratePDF', {
        documentPath: `PDFs/${documentName(fileName)}`,
        fullPath: mainPath,
        title: 'Generate PDF from HTML string'
description: ""
    });
    } catch (e) {
        console.log(e.message, e.code);
        alert(e.message);
    }

Generating PDF Documents from a URL

To generate a PDF document from a URL, use the Processor class that takes a configuration object and the URL as its parameters:

try {
    fileURL = await getOutputPath(fileName);
} catch (e) {
    console.log(e.message, e.code);
    alert(e.message);
}

const configuration = {filePath: fileURL, override: true};
let originURL = 'https://pspdfkit.com';

try {
    let { fileURL: outputURL } = await Processor.generatePDFFromHtmlURL(configuration,originURL);
} catch (e) {
    console.log(e.message, e.code);
    alert(e.message);
}

See the list with all the configuration options you can use with Processor.

To test this functionality, see the demo projects in the Catalog and the NativeCatalog apps.