You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Proposal: Allow authors to programmatically "save as PDF" #7946
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.
Reacted by Maximilian Franzke, clem, Umang Galaiya, Mike Owens, Anthony, Murat Çorlu, Jimmy Wärting, Laytan, Gautam Chaudhary, Thomas Orlita and 42 more
Reacted by LanderBeeuwsaert, clem, Wil Marques, Minjun Kim, Chris Heinz, Lucas Said, thewh1teagle, Vighnesh Raut, Nina Sjöberg, Anoesj Sadraee and 1 more
Reacted by LanderBeeuwsaert, clem, Alex Jung Celmer, Wil Marques, Simon Bluhm, Minjun Kim, Chris Heinz, Lucas Said, muttalib-github, Gabriel Sepulveda and 7 more
Reacted by Lucas Said, thewh1teagle and Vighnesh Raut
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.
@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:
interfacePrintOptions{saveAsPDF?: boolean;// always sets "save as PDF" as the destinationprint?: boolean;// always sets "print" as the destinationsettings?: {layout?: "portrait"|"landscape";margins?: {all?: number;// top, bottom, left, rightvertical?: number;// top, bottomhorizontal?: number;// left, righttop?: number;bottom?: number;left?: number;right?: number;};scale?: number;informationalText?: boolean;// headers and footersbackgroundGraphics?: boolean;};}
Reacted by Wil Marques, Mariano Franzese, Bibin, Théo LUDWIG, Vighnesh Raut, KurtShine and David Obdržálek [ΔO]
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?
Reacted by LanderBeeuwsaert, Benjamin Aster, Moshe Brevda, Mark Bennett, Simon Bluhm and Wil Marques
@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.
@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" })?
Reacted by Thomas Steiner, Simon Bluhm and Mr Beedell, Roke Julian Lockhart
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.
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).
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
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:
Allow saving a page or a specific subsection of a page (e.g. a receipt, invoice, or report component) directly to PDF.
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).
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:
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.
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:
Return Promise
Resolves the promise with a FileSystemFileHandle
Rejects the promise with AbortError when dismissed
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 DOMExceptionawaitnavigator.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 SecurityErrorDOMException.
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.
Reacted by Laurens, Almior Ansano, Daniel Beeke, ysgk, Ajay Chauhan, Mariana Rodrigues, Berat BAYRAM, JingAn Chen, Kushal Krishna and Simon Bluhm
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?
Reacted by Anoesj Sadraee, Théo LUDWIG, Simon Bluhm, Staffan Al-Kadhimi and sillyas2010
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.
Activity
arya-vats commentedon May 21, 2022
BenjaminAster commentedon May 21, 2022
anaestheticsapp commentedon May 26, 2022
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.BenjaminAster commentedon May 26, 2022
@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
settingsoption 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 theWindow.print()parameter object could look like:mbrevda commentedon May 26, 2022
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?
BenjaminAster commentedon May 26, 2022
@mbrevda Ok, you're absolutely right! I've never looked into
@pagebefore, but yes, it seems all those things can actually already be done with just pure CSS. Size and layout can be controlled viasize, margins viamargin, the headers and footers can be hidden by setting the@pagemargin to 0 (and then giving the body a margin manually with@media print), and background graphics can be enabled via theprint-color-adjust: exactCSS property (Chromium needs a-webkit-prefix here).So I guess the
settingsoption would actually be redundant here.tomayac commentedon May 27, 2022
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:
If there were a way to pass a selector like
.receipt, the user could create a PDF from only a subsection.BenjaminAster commentedon May 27, 2022
@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 adisplay: 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" })?MrVoshel commentedon May 27, 2022
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
Creatorand the moment you downloaded the pdf asCreationDate, which seems strange if the documents report another date.anaestheticsapp commentedon May 28, 2022
Interesting - didn't know about
print-color-adjust: exactand@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.
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).mbrevda commentedon May 28, 2022
To simplify the API surface, perhaps the ability to print could be added to any element, like
someSelector.saveAsPdf()olejorgenb commentedon Apr 3, 2024
👍 In some situations it would be nice to have the ability to get the printed PDF file programmatically
feat: create a resume builder page for vighnesh153.dev
sbearduu commentedon Apr 9, 2025
Anoesj commentedon Aug 27, 2025
Related/similar: #10612
[-]Proposal: Allow authors to enforce "save as PDF" when printing a document[/-][+]Proposal: Allow authors to programmatically "save as PDF"[/+]window.exportPdf(), Leveraging Browser's Print Save As PDF functionality #10612 as a duplicate of this issueAnoesj commentedon Aug 28, 2025
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):@annevk Could you provide some thoughts on if the proposal in this issue might be considered viable with the following boundaries:
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:What solutions exist today?
Developers currently have to resort to custom solutions and hacks, such as:
<iframe>+window.print()hackThese third-party libs, especially when used client-side, have big disadvantages:
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:
How would you solve it?
A better DX and UX could be achieved by adding a new Web API method, either on the
windowobject or under anavigatornamespace object likenavigator.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 bywindow.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:
Promiseresolving withundefinedor rejecting with aDOMException, such asAbortErrororSecurityError.The proposed method would be available under
windowor anavigatornamespace object. I have the following suggestions:navigator.download.asPdf(see: Download API #4148)navigator.export.saveAsPdfnavigator.export.asPdfwindow.saveAsPdfI lean towards
navigator.download.asPdf, as thenavigator.downloadnamespace could later accommodate other possibly interesting export targets (e.g.asText, orasImagefor 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
showSaveFilePickermethod:target(optional)Elementto generate a PDF for. Defaults todocument.documentElement.suggestedName(optional)startIn(optional)"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". WhencssMediais"screen",@media printstyles 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.showSaveFilePickerbehaves as follows:PromiseFileSystemFileHandleAbortErrorwhen dismissedSecurityErrorin several scenarios (e.g. see: https://wicg.github.io/file-system-access/#local-file-system-permissions)However, I don't think we need a
FileSystemFileHandlein the discussed API, so our return signature could bePromise<void>, I think.Example:
Anything else?
Security
This method should probably require transient activation, just like
window.showSaveFilePicker. If called without user activation, it would throw aSecurityErrorDOMException.t.b.d. — Any input from experts is greatly appreciated!
I'm particularly curious about the following situations:
FileSystemHandleis passed tostartIn, 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 acceptWellKnownDirectoryenum values forstartIn, not handles, keeping the start-location hint without the option to read immediately afterwards.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.documentElementis currently possible in any of the major browsers.CSS
printvs.screenstylesI'm curious to hear thoughts on whether the API should and could allow exporting to PDF while applying the
screenstyles, instead ofprintstyles. 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, withtargetandcssMedia: "screen"as progressive enhancements.Midwayne commentedon Jun 4, 2026
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?
annevk commentedon Jun 5, 2026
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
downloadattribute) and this would essentially be a special case of that.