Skip to content

Proposal: Allow authors to programmatically "save as PDF" #7946

Open

Description

@BenjaminAster

There are several use cases where it would be handy to be able to show a "save as PDF" dialog programmatically. For example, a document editing application might want to allow their users to export the document as a PDF without using any PDF generation library. While most user agents already allow users to select a "save as PDF" option when a document is printed (e.g. when Window.print() is called), there is currently no possibility for the author to hint the browser that the print dialog should be shown with the "save as PDF" option enabled.

I am proposing an addition to the Window.print() method with an optional parameter that allows authors to tell the user agent the way that the print dialog should be shown:

// The destination of the user agent's print dialog becomes "save as PDF", even if it would have been "print" otherwise.
window.print({ saveAsPDF: true });

If the user agent is not able to provide a way to export the document as a PDF, it may ignore this option.

Activity

  1. arya-vats commented on May 21, 2022

    @arya-vats
  2. BenjaminAster commented on May 21, 2022

    @BenjaminAster
    Author
  3. added
    addition/proposal
    needs implementer interest
    on May 21, 2022
  4. anaestheticsapp commented on May 26, 2022

    @anaestheticsapp

    Saving a document as a PDF can be surprisingly complex for the average end user, so I think this is desparately needed. I like the idea of window.print({ saveAsPDF: true });, but there should also be an option to change the default print settings, such as "Landscape" for layout, enabling "Background graphics" and the ability to change scale and margins.

  5. BenjaminAster commented on May 26, 2022

    @BenjaminAster
    Author

    Note
    The idea described in the following comment is redundant because, as @mbrevda pointed out, all of these things can be done with pure CSS. I'll keep my original comment here so that the conversation makes sense:

    @anaestheticsapp Great idea! If author-controlled options like layout or background graphics would be implemented, I think it would make sense here to make them universally available for both printing and saving as a PDF. I'd suggest an additional settings option where the author could tell the user agent how the print layout should look by default. The user should then be able to customize these settings in the browser's native printing dialog. The following is an example of how the Window.print() parameter object could look like:

    interface PrintOptions {
    	saveAsPDF?: boolean; // always sets "save as PDF" as the destination
    	print?: boolean; // always sets "print" as the destination
    	settings?: {
    		layout?: "portrait" | "landscape";
    		margins?: {
    			all?: number; // top, bottom, left, right
    			vertical?: number; // top, bottom
    			horizontal?: number; // left, right
    			top?: number;
    			bottom?: number;
    			left?: number;
    			right?: number;
    		};
    		scale?: number;
    		informationalText?: boolean; // headers and footers
    		backgroundGraphics?: boolean;
    	};
    }
  6. mbrevda commented on May 26, 2022

    @mbrevda

    As an alternative to passing print options, would it make sense to specify them via CSS using Paged Media where all these (and much more) are already specified?

  7. BenjaminAster commented on May 26, 2022

    @BenjaminAster
    Author

    @mbrevda Ok, you're absolutely right! I've never looked into @page before, but yes, it seems all those things can actually already be done with just pure CSS. Size and layout can be controlled via size, margins via margin, the headers and footers can be hidden by setting the @page margin to 0 (and then giving the body a margin manually with @media print), and background graphics can be enabled via the print-color-adjust: exact CSS property (Chromium needs a -webkit- prefix here).

    So I guess the settings option would actually be redundant here.

  8. tomayac commented on May 27, 2022

    @tomayac

    One thing that was brought up was the ability to not convert the entire page to PDF, but just a subsection of it, for example, for printing receipts:

    <body>
      <section><!-- App UI --></section>
      <section class="receipt">
        <h1>Receipt</h1>
        <ul><!-- Receipt contents --></ul>
      </section>
      <section><!-- App UI --></section>
    </body>

    If there were a way to pass a selector like .receipt, the user could create a PDF from only a subsection.

  9. BenjaminAster commented on May 27, 2022

    @BenjaminAster
    Author

    @tomayac This can already be done (with a bit of effort) by re-layouting the whole page with @media print {} (as described in my Chromium Monorail comment) so that one element (in this case the <section class="receipt">) fills in the whole page, and everything else (in this case the app UI elements) gets a display: none.

    But yes, I agree that it would be convenient to specify an element that gets printed individually and without some hacky CSS solution. Maybe something like window.print({ saveAsPDF: true, selector: "section.receipt" })?

  10. MrVoshel commented on May 27, 2022

    @MrVoshel

    It would be useful to be able to edit the metadata. For example as of now I think it's only possible to have the user agent as Creator and the moment you downloaded the pdf as CreationDate, which seems strange if the documents report another date.

    image

  11. anaestheticsapp commented on May 28, 2022

    @anaestheticsapp

    Interesting - didn't know about print-color-adjust: exact and @page { size: landscape; }, that's actually solving half my problems!

    Instead of having a boolean, another option could be to just pass the HTML element into saveAsPDF.

    window.print({ saveAsPDF: document.body })
    window.print({ saveAsPDF: document.querySelector('section.receipt') })

    Agree, would make sense to be able to specify metadata when generating the PDF document. I guess the browser could just use the data already provided by HTML <meta> tags.

    <meta name="pdf:title" content="Receipt"> could be used if the page generates a PDF from a subsection (as it would likely differ from the title of the HTML document).

  12. mbrevda commented on May 28, 2022

    @mbrevda

    To simplify the API surface, perhaps the ability to print could be added to any element, like someSelector.saveAsPdf()

  13. olejorgenb commented on Apr 3, 2024

    @olejorgenb

    To simplify the API surface, perhaps the ability to print could be added to any element, like someSelector.saveAsPdf()

    👍 In some situations it would be nice to have the ability to get the printed PDF file programmatically

  14. sbearduu commented on Apr 9, 2025

    @sbearduu
  15. Anoesj commented on Aug 27, 2025

    @Anoesj

    Related/similar: #10612

  16. changed the title [-]Proposal: Allow authors to enforce "save as PDF" when printing a document[/-] [+]Proposal: Allow authors to programmatically "save as PDF"[/+] on Aug 28, 2025
  17. Anoesj commented on Aug 28, 2025

    @Anoesj

    A bit of context about the referenced issue (now closed). This proposal was a bit different, as it suggested adding an API that would generate a PDF as an ArrayBuffer, which would lead to security issues. This was pointed out by @annevk in #10612 (comment):

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

    @annevk Could you provide some thoughts on if the proposal in this issue might be considered viable with the following boundaries:

    • Scripts do not get access to the generated PDF, its contents or its file handle.
    • The UA generates the PDF and shows the save dialog.
    • Optional: user activation is required.

    I would also like to add my two cents regarding the API and provide some motivation mentioned earlier by @apurvaojas in #10612, supplemented with my own views for completeness.

    What problem are you trying to solve?

    Web developers often need to generate a PDF representation of their content. 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. Exporting as PDF through this approach is suboptimal and results in poor UX for end users, because sometimes downloading as PDF is the intention, not printing. Furthermore, this always targets the entire document and always applies print styles. This is useful for end-user printing, but it is not sufficient for common scenarios such as:

    • Exporting a specific subsection of a page (e.g. a receipt, invoice, or report component).
    • Producing a PDF with the screen styling (e.g. branded documents that should match the on-screen look, not the print stylesheet).
    • Controlling suggested and/or definitive PDF output options (page size, orientation, margins, scaling) when print styles are not applied.

    What solutions exist today?

    Developers currently have to resort to custom solutions and hacks, such as:

    • Server-side PDF generation using third-party libs or rendering a web page to PDF using a headless browser like Puppeteer
    • Client-side PDF generation using third-party libs, like jsPDF/PDF.js/pdfkit, along with a <iframe> + window.print() hack

    These third-party libs, especially when used client-side, have big disadvantages:

    • Inconsistency across browsers
    • Significant performance and rendering issues, especially with large or complex pages
    • They can be overly complex when generating PDFs from dynamic, styled content
    • Limited support for maintaining CSS and layout fidelity
    • Complex setup and additional dependencies
    • Increased bundle size / downloaded bytes

    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. A standardized client-side API would improve consistency, interoperability and remove the need for heavy workarounds.

    Therefore, this proposal has the following goals:

    1. Allow saving a page or a specific subsection of a page (e.g. a receipt, invoice, or report component) directly to PDF.
    2. Allow producing a PDF with the print or screen styling applied (e.g. for branded documents that should match the on-screen look, not the print stylesheet).
    3. Optional: controlling suggested and/or definitive PDF output options (page size, orientation, margins, scaling) when print styles are not applied.

    How would you solve it?

    A better DX and UX could be achieved by adding a new Web API method, either on the window object or under a navigator namespace object like navigator.export (if "export" would not cause any problems or confusion with ESM modules at least). This method will allow developers to programmatically generate a PDF of a web page or specified DOM elements, showing a save file dialog, so the PDF can be saved to disk directly. The API can leverage the browser's built-in PDF generation (the same functionality used by window.print()) whenever print styles should be applied and the entire web page is exported to PDF. For any other scenarios, I am open to suggestions and ideas from the community and specialists on the topic.

    Key features of the proposed API:

    • Programmatic PDF generation and save capability: The API will trigger the UA to generate a PDF and show a save file dialog. It returns a Promise resolving with undefined or rejecting with a DOMException, such as AbortError or SecurityError.
    • Native performance: The API will use native browser capabilities, ensuring faster and more reliable PDF generation compared to third-party libraries.

    The proposed method would be available under window or a navigator namespace object. I have the following suggestions:

    • navigator.download.asPdf (see: Download API #4148)
    • navigator.export.saveAsPdf
    • navigator.export.asPdf
    • window.saveAsPdf

    I lean towards navigator.download.asPdf, as the navigator.download namespace could later accommodate other possibly interesting export targets (e.g. asText, or asImage for programmatically taken screenshots of a page or sections of it), and the underlying functionality is essentially unrelated to printing.

    The method would take an optional options object, that shares some options with File System Access API's showSaveFilePicker method:

    • target (optional)
      • An Element to generate a PDF for. Defaults to document.documentElement.
    • suggestedName (optional)
      • A String. The suggested file name.
    • startIn (optional)
      • A FileSystemHandle or a well known directory ("desktop", "documents", "downloads", "music", "pictures", or "videos") to open the dialog in.
    • cssMedia (optional)
      • "print" or "screen", stating what CSS media's styles to apply. Defaults to "print". When cssMedia is "screen", @media print styles are ignored entirely. The document is rendered as if no print stylesheet exists.

    Up for debate is what the exact return value should be. window.showSaveFilePicker behaves as follows:

    However, I don't think we need a FileSystemFileHandle in the discussed API, so our return signature could be Promise<void>, I think.

    Example:

    // Promise<void>, could reject with DOMException
    await navigator.download.asPdf({
      target: document.documentElement,
      suggestedName: 'invoice.pdf',
      startIn: 'downloads',
      cssMedia: 'print',
    });

    Anything else?

    Security

    This method should probably require transient activation, just like window.showSaveFilePicker. If called without user activation, it would throw a SecurityError DOMException.

    t.b.d. — Any input from experts is greatly appreciated!

    I'm particularly curious about the following situations:

    • When a FileSystemHandle is passed to startIn, it would in theory be possible for the script to read the file immediately after saving, since a directory handle retains its permissions. This would be insecure. This conflicts with the "scripts get no access to the generated PDF" boundary. A possible mitigation: only accept WellKnownDirectory enum values for startIn, not handles, keeping the start-location hint without the option to read immediately afterwards.
    • When the script did not use startIn, but has requested and received access to the directory the exported PDF has been downloaded into using the File System Access API, this might be a security issue too.

    Current UA PDF generation capabilities

    As I'm not an expert on the topic, I'd like to know if rendering a DOM element other than document.documentElement is currently possible in any of the major browsers.

    CSS print vs. screen styles

    I'm curious to hear thoughts on whether the API should and could allow exporting to PDF while applying the screen styles, instead of print styles. I'm aware I haven't fully thought this through and it could be a future enhancement, let me know your thoughts! It is currently unclear to me whether UAs can render an arbitrary DOM element in isolation with screen styles applied. Feedback from browser implementors on feasibility is welcome.

    Progressive enhancements

    To keep the initial scope minimal, the whole-document + print-styles case (essentially window.print() without the print-dialog detour) could land first, with target and cssMedia: "screen" as progressive enhancements.

  18. Midwayne commented on Jun 4, 2026

    @Midwayne

    Is this proposal still actively being considered? I run into this limitation frequently when building stuff and the current workarounds (like server-side generation or complex print stylesheets) are very brittle for users. I'd love to see the API proposed by @Anoesj move forward. Is there anything the community can do to help demonstrate implementer interest?

  19. annevk commented on Jun 5, 2026

    @annevk
    Member

    I don't think it's actively considered right now, but that can always change. I think what @Anoesj proposed makes sense. The one thing that's giving me pause is that we haven't really figured out a minimal download API (#4148) yet (if we ignore the download attribute) and this would essentially be a special case of that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    addition/proposalneeds implementer interest

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions