whatwg / html

HTML Standard
https://html.spec.whatwg.org/multipage/
Other
8.03k stars 2.62k forks source link

Automated `window.exportPdf()`, Leveraging Browser's Print Save As PDF functionality #10612

Open apurvaojas opened 1 week ago

apurvaojas commented 1 week ago

What problem are you trying to solve?

Generating a PDF from a web page today is primarily achieved through the window.print() API, which requires user interaction (via a print dialog) to save the page as a PDF. This approach lacks programmatic control and is not suitable for headless or automated environments where PDFs need to be generated and handled directly by the application. Developers are forced to rely on third-party libraries (e.g., jsPDF), which:

The current methods do not provide a native, efficient way to export a web page or specific parts of it as a PDF programmatically, leading to fragmentation and varied developer experience across applications and platforms.

What solutions exist today?

  1. window.print() API:

    • Pros: It leverages the native browser’s PDF generation capabilities via the print dialog.
    • Cons: It requires user interaction and cannot be automated for scenarios like Exporting of report from UI, From UX point of view its hard for users to print and save as pdf, as it is not the default selection.
  2. Third-party libraries (e.g., jsPDF, html2pdf):

    • Pros: Offer programmatic control over PDF creation, enabling developers to generate PDFs without user interaction.
    • Cons:
      • Complex setup and additional dependencies.
      • Inconsistent output across browsers.
      • Performance issues with large or complex pages.
      • Limited support for maintaining CSS and layout fidelity.

How would you solve it?

We propose adding a new window.exportPdf() API to the HTML DOM. This method will allow developers to programmatically generate a PDF of a web page or specified DOM elements, returning the PDF data as an ArrayBuffer. The API will leverage the browser's built-in PDF generation (the same functionality used by window.print()), but without requiring user interaction.

Key features of the proposed API:

window.exportPdf()
  .then(pdfBuffer => {
      // use buffer to automatically download file or Open SaveAs Dialog
  })
  .catch(error => {
      console.error("PDF generation failed:", error);
  });

This approach addresses the pain points of current solutions by:

Anything else?

This API would simplify PDF generation tasks for developers, improve performance, and reduce reliance on third-party libraries, leading to more consistent user experiences across the web.

annevk commented 1 day ago

This isn't viable for the same reason we don't support screenshots. That would leak information about what is displayed on the page.

flashymittens commented 12 hours ago

Shouldn’t it simply show Save As dialog? If you want to modify the result, simply build a DOM you want before you export it.