ArticleZip > Pdf Js Rendering A Pdf File Using A Base64 File Source Instead Of Url

Pdf Js Rendering A Pdf File Using A Base64 File Source Instead Of Url

Would you like to render a PDF file using a base64 file source instead of a URL with PDF.js? This handy feature allows you to easily manipulate PDF files within your web application without the need for hosting them on external servers. In this article, we'll guide you through the process of achieving this using PDF.js, a popular JavaScript library for working with PDF files in the browser.

To begin, ensure you have a base64 representation of your PDF file. If you are unfamiliar with base64 encoding, it is a method of encoding binary data into ASCII string format. You can easily obtain the base64 representation of a file using various online tools or by writing a simple script to encode your PDF file.

Next, include PDF.js in your project. You can either download the library or use a content delivery network (CDN) link to include it in your HTML file. Remember to add a canvas element to your HTML where the PDF will be rendered. Here's a basic example of how you can set up the necessary elements:

Html

Now, let's move on to the JavaScript part. You will need to write a script to fetch the base64 data, decode it, and render the PDF using PDF.js. Below is a simplified version of the script:

Javascript

// Decode your base64 PDF file
let pdfData = atob(yourBase64Data);
// Create a new Uint8Array from the decoded base64 data
let pdfArray = new Uint8Array(pdfData.length);
for (let i = 0; i  {
    pdf.getPage(1).then(page => {
        let scale = 1.5;
        let viewport = page.getViewport({ scale });
        let canvas = document.getElementById('pdf-render');
        let context = canvas.getContext('2d');
        canvas.height = viewport.height;
        canvas.width = viewport.width;
        page.render({ canvasContext: context, viewport });
    });
});

In the above script, make sure to replace `yourBase64Data` with your actual base64-encoded PDF data. This script decodes the base64 data, creates a Uint8Array, and then renders the PDF onto the canvas element we defined earlier.

Once you have set up the script, load your HTML file in a browser, and you should see your PDF file rendered on the canvas.

By following these steps, you can easily render a PDF file using a base64 file source instead of a URL using PDF.js. This method provides a convenient way to work with PDF files directly within your web application. Experiment with additional features provided by PDF.js to further enhance your PDF rendering capabilities. Happy coding!