Ausnahme gefangen: SSL certificate problem: certificate is not yet valid ๐Ÿ“Œ Creating PDF Files Without Slowing Down Your App

๐Ÿ  Team IT Security News

TSecurity.de ist eine Online-Plattform, die sich auf die Bereitstellung von Informationen,alle 15 Minuten neuste Nachrichten, Bildungsressourcen und Dienstleistungen rund um das Thema IT-Sicherheit spezialisiert hat.
Ob es sich um aktuelle Nachrichten, Fachartikel, Blogbeitrรคge, Webinare, Tutorials, oder Tipps & Tricks handelt, TSecurity.de bietet seinen Nutzern einen umfassenden รœberblick รผber die wichtigsten Aspekte der IT-Sicherheit in einer sich stรคndig verรคndernden digitalen Welt.

16.12.2023 - TIP: Wer den Cookie Consent Banner akzeptiert, kann z.B. von Englisch nach Deutsch รผbersetzen, erst Englisch auswรคhlen dann wieder Deutsch!

Google Android Playstore Download Button fรผr Team IT Security



๐Ÿ“š Creating PDF Files Without Slowing Down Your App


๐Ÿ’ก Newskategorie: Programmierung
๐Ÿ”— Quelle: dev.to

In many web applications, there are times when we need to generate and download PDF files on the client-side. However, for the sake of showing a live preview to users, PDF generation may block the main thread and cause poor user experience. This is where web workers come into play. In this article, we will explore how to use @react-pdf/renderer inside a web worker to render PDF files in a non-blocking way.

What is react-pdf?

@react-pdf/renderer is an open-source library that enables developers to create and render PDF documents using React components, which allows developers to use a familiar declarative syntax. @react-pdf/renderer provides a set of built-in components for creating basic PDF elements such as text, images and links. Itโ€™s engine-agnostic and can run both inside the browser and NodeJS.

What are Web Workers?

A web worker is a JavaScript that runs in the background, separate from the main thread. It allows us to perform long-running tasks without blocking the main thread, which can improve the overall performance and user experience of an application. Web workers can communicate between each other and the main thread via messages. Web worker should primarily be used for long-running tasks, as managing web workers and sending data between them has performance implications.

Final Result

Checkout the repo here or the stackblitz demo here

How it all comes together?

Before we get into the details of using web workers, letโ€™s start by creating a simple react pdf component. Hereโ€™s an example:

import { Page, Document, Text } from '@react-pdf/renderer';

export type PDFProps = {
  title: string;
  author: string;
  description: string;
};

export const PDF = (props: PDFProps) => (
  <Document title={props.title} author={props.author} subject={props.description}>
    <Page>
      <Text>Hello, World!</Text>
    </Page>
  </Document>
);

This component creates a PDF document with a single page that says, โ€œHello, World!โ€.

Creating a RenderPDF Function

Now that we have a PDF component, we need a way to convert it to a PDF file. We can do this using the toBlob method of the pdf function provided by @react-pdf/renderer. Hereโ€™s an example of a function that does this:

import { createElement } from 'react';
import type { PDFProps } from './PDF';

export const renderPDF = async (props: PDFProps) => {
  const { pdf } = await import('@react-pdf/renderer');
  const { PDF } = await import('./PDF');
  return pdf(createElement(PDF, props)).toBlob();
};

This function takes a PDFProps object as an argument, creates a PDF element using createElement, and then passes it to the pdf function provided by @react-pdf/renderer. Finally, it returns a Blob object representing the PDF file.

Creating a Web Worker

Now that we have a way to create PDF files, we can create a web worker to run the renderPDF function in a separate thread. Hereโ€™s an example of a web worker that uses comlink to expose the renderPDF function as an asynchronous function:

import { expose } from 'comlink';
import type { PDFProps } from '../PDF';
import './workerShim';
let log = console.info;

const renderPDFInWorker = async (props: PDFProps) => {
  try {
    const { renderPDF } = await import('../renderPDF');
    return URL.createObjectURL(await renderPDF(props));
  } catch (error) {
    log(error);
    throw error;
  }
};

const onProgress = (cb: typeof console.info) => (log = cb);

expose({ renderPDf, onProgress });

export type WorkerType = {
  renderPDf: typeof renderPDf;
  onProgress: typeof onProgress;
};

This code imports the renderPDF() function we created earlier, and exposes the renderPDFInWorker as an asynchronous function, which returns the blob URL using comlink. The onProgress function is used for debugging purposes to pipe the output back to main thread console.

Integrating it into the application

By now having this simple async function, there is no requirement to use React as the main thread ui framework. Theoretically, it could be used in a jQuery or vanilla JS application.

The react implementation would look like this:

import { useEffect } from "react";
import { useAsync } from "react-use";
import { proxy, wrap } from "comlink";
import type { WorkerType } from "./workers/pdf.worker";
import Worker from "./workers/pdf.worker?worker";

export const pdfWorker = wrap<WorkerType>(new Worker());
pdfWorker.onProgress(proxy((info: any) => console.log(info)));

export const useRenderPDF = ({
  title,
  author,
  description,
}: Parameters<WorkerType["renderPDFInWorker"]>[0]) => {
  const {
    value: url,
    loading,
    error,
  } = useAsync(async () => {
    return pdfWorker.renderPDFInWorker({ title, author, description });
  }, [title, author, description]);

  useEffect(() => (url ? () => URL.revokeObjectURL(url) : undefined), [url]);
  return { url, loading, error };
};

To import the PDF worker, this example uses viteโ€™s query suffixes import syntax. After that, the worker is wrapped by comlink.

The useRenderPDF hook now takes in the PDF component props as its argument. It then uses the useAsync hook to call the renderPDFInWorker function, passing the component props to it and returning a value, error and loading state.

Finally, the useEffect hook is used to clean up the URL object created by the renderPDFInWorker function to prevent memory leaks.

Improvements & Considerations

To minimize communication overhead, it was explicitly opted to send the component props instead of the complete v-dom, and thus this implementation is not as flexible as the non web worker implementation.

A potential improvement could therefore be to make it easier to use renderPDFInWorker with multiple different PDFs via the use of the factory pattern and inline workers.

The implementation was only tested in vite and required shims to make @react-pdf/renderer work inside a web worker, which may need to be adapted to work in other bundlers

In vites current setup, it doesnโ€™t allow even ESM web workers to share code chunks with the main bundle. Thus, the bundle will include @react-pdf/renderer, react and all other libraries that both the PDF component and the main bundle uses twice.

Conclusion

In this article, weโ€™ve explored how to use @react-pdf/renderer inside a web worker to generate PDF files in a non-blocking way. Weโ€™ve used the comlink library to communicate with the worker and create a promise-based API wrapper.

...



๐Ÿ“Œ Creating PDF Files Without Slowing Down Your App


๐Ÿ“ˆ 63.97 Punkte

๐Ÿ“Œ Catch the Most Sophisticated Attacks Without Slowing Down Your Users


๐Ÿ“ˆ 35.87 Punkte

๐Ÿ“Œ The Kernel Change That May Be Slowing Down Your App


๐Ÿ“ˆ 30.83 Punkte

๐Ÿ“Œ How To Merge PDF Files? Easy Steps To Combine PDF Files


๐Ÿ“ˆ 29.52 Punkte

๐Ÿ“Œ Creating Self-Serve DevOps Without Creating More Toil


๐Ÿ“ˆ 28.67 Punkte

๐Ÿ“Œ Is Windows Defender slowing down your computer?


๐Ÿ“ˆ 27.77 Punkte

๐Ÿ“Œ Is Your RAM Slowing You Down?


๐Ÿ“ˆ 27.77 Punkte

๐Ÿ“Œ How to Keep Your Windows PC from Slowing Down


๐Ÿ“ˆ 27.77 Punkte

๐Ÿ“Œ March 2023 Patch Tuesday update is seriously slowing down your SSD


๐Ÿ“ˆ 27.77 Punkte

๐Ÿ“Œ Daemons and Agents could be slowing down your Mac


๐Ÿ“ˆ 27.77 Punkte

๐Ÿ“Œ Creating and Analyzing a Malicious PDF File with PDF-Parser Tool


๐Ÿ“ˆ 25.68 Punkte

๐Ÿ“Œ rsync: how to copy files without creating duplicates?


๐Ÿ“ˆ 25.45 Punkte

๐Ÿ“Œ Severe security bug found in popular PHP library for creating PDF files


๐Ÿ“ˆ 25.04 Punkte

๐Ÿ“Œ More Data Saying Chinese Attacks Are Slowing Down (June 21, 2016)


๐Ÿ“ˆ 24.26 Punkte

๐Ÿ“Œ The iPhone Remade Apple 10 Years Ago. Now Itโ€™s Slowing Apple Down


๐Ÿ“ˆ 24.26 Punkte

๐Ÿ“Œ More Data Saying Chinese Attacks Are Slowing Down (June 21, 2016)


๐Ÿ“ˆ 24.26 Punkte

๐Ÿ“Œ The iPhone Remade Apple 10 Years Ago. Now Itโ€™s Slowing Apple Down


๐Ÿ“ˆ 24.26 Punkte

๐Ÿ“Œ How I solved a trick problem slowing down my computer


๐Ÿ“ˆ 24.26 Punkte

๐Ÿ“Œ Apple Is Now Being Sued for Slowing Down Older iPhone Devices


๐Ÿ“ˆ 24.26 Punkte

๐Ÿ“Œ Apple Hit With Class Action Lawsuit After Admitting To Slowing Down Old iPhones


๐Ÿ“ˆ 24.26 Punkte

๐Ÿ“Œ Angry iPhone Users Want Apple to Pay $999 Billion for Slowing Down Devices


๐Ÿ“ˆ 24.26 Punkte

๐Ÿ“Œ Apple Apologizes for Slowing Down Old iPhones, Offers $29 Battery Replacements


๐Ÿ“ˆ 24.26 Punkte

๐Ÿ“Œ b00merang themes project slowing down


๐Ÿ“ˆ 24.26 Punkte

๐Ÿ“Œ if i create a swap file on an ext4 filesystem, will the ext4 journal the swap file writes, slowing down performance?


๐Ÿ“ˆ 24.26 Punkte

๐Ÿ“Œ Apple and Samsung punished for slowing down old smartphones


๐Ÿ“ˆ 24.26 Punkte

๐Ÿ“Œ Linux kernel Spectre V2 defense fingered for massively slowing down unlucky apps on Intel Hyper-Thread CPUs


๐Ÿ“ˆ 24.26 Punkte

๐Ÿ“Œ Unlike Apple, Android Companies Say Theyโ€™re Not Slowing Down Older Phones


๐Ÿ“ˆ 24.26 Punkte

๐Ÿ“Œ Math Says You're Driving Wrong and It's Slowing Us All Down


๐Ÿ“ˆ 24.26 Punkte

๐Ÿ“Œ US Government Launches Investigation into Apple Over Slowing Down iPhones


๐Ÿ“ˆ 24.26 Punkte

๐Ÿ“Œ Apple Says It Admitted Slowing Down iPhones As โ€œIt Was the Right Thing to Doโ€


๐Ÿ“ˆ 24.26 Punkte

๐Ÿ“Œ Microsoft Teams growth is pretty strong and it's not slowing down


๐Ÿ“ˆ 24.26 Punkte

๐Ÿ“Œ Microsoft Teams growth is pretty strong and it's not slowing down


๐Ÿ“ˆ 24.26 Punkte











matomo