How trigger browser to make a PDF from HTML using window.print()
Here is how you can create a pdf from html/css on the client side (no backend or external libraries involved). We will take advantage of the window.print() and some specific CSS. Unfortunately, this will not work on mobile browsers (as pointed out in the comments). Needed styles for the window.print() function:
* font-family: Arial, Helvetica, sans-serif; color: rgb(65, 65, 65); -webkit-print-color-adjust: exact !important; color-adjust: exact !important; print-color-adjust: exact !important; > @media print @page margin-left: 0.8in; margin-right: 0.8in; margin-top: 0; margin-bottom: 0; > > #container width: 800px; margin: 0 auto; >
Of course, you can set other values for font-family , color and #container . Add the rest of the styles for your custom pdf. Next, we need to trigger the window.print() function which is native to the browser. So add below js in a script tag.
document.addEventListener("DOMContentLoaded", () => let printLink = document.getElementById("print"); let container = document.getElementById("container"); printLink.addEventListener("click", event => event.preventDefault(); printLink.style.display = "none"; window.print(); >, false); container.addEventListener("click", event => printLink.style.display = "flex"; >, false); >, false);
lang="en"> charset="UTF-8"> http-equiv="X-UA-Compatible" content="IE=edge"> name="viewport" content="width=device-width, initial-scale=1.0"> This will be the title of the pdf file id="container"> href="#" id="print">GENERATE PDF! Super cool custom pdf This pdf is generated from the client side without any external libraries!
Top comments (47)
Kind of a misleading article. This really doesn’t have anything to do with generating a PDF — it just tells you how to kick your browser to print the current page. The fact that the print dialog may have an option to «Print to PDF» is entirely separate to anything you are doing here — and will likely be dependent on your browser and system. You’ll still have to select ‘Print to PDF’ manually
75 likes Like Comment button
But still this is a great article 👍 Keep it up
8 likes Like Comment button
Independent contractor interested in web development and business automation. Contact me on Linkedin.
6 likes Like Comment button
Independent contractor interested in web development and business automation. Contact me on Linkedin.
Fixed, modified title. Hopefully it’s more clear now.
Would be nice if browsers would have some native api’s for pdf generation..
2 likes Like Comment button
No. It’s better this way. There are other ways you can manage «pdfs» while this tool does all of that and much more. i.e. Print as well.
Not everything needs changing. You wrote a good article. Sure had a wrong title, I wont call it misleading personally. Misleading would be when you’d do that knowingly. Just stick to your findings. Don’t defend yourself when you find contradicting information proving you wrong. But don’t back down either if otherwise.
4 likes Like Comment button
Founder Of @Bytemakers 😎 || Full Stack Developer 🤓 || Building @RepoCraft 🚀|| Open Source 💪 || DevOps 🌩️ || UIUX Developer 📊 || Technical Writer 👨 || Friendly Moderator & Trusted Member at DEV.
Fr. We have Print to PDF in the browser itself. And most modern browsers support it.
1 like Like Comment button
Why to use js to toggle print button.
This can be achieved by something like as below
So basically we can assign a new value to css in print selector.
15 likes Like Comment button
Independent contractor interested in web development and business automation. Contact me on Linkedin.
3 likes Like Comment button
Never ever style id’s in your css. id’s are for js only, classes are good for styling. If for some reason you will need the same functionality in other place it will be better to assign a class for it.
The same goes to !important notation. Usually there is no reason to use it because it’s hard to override it.
6 likes Like Comment button
Software dev specializing in privacy & infosec. Indie gamedev over enterprise. People over profit. ¯\_(ツ)_/¯. Basic income for all, direct democracy now. CBDC’s will END privacy.
It’s perfectly fine to style id’s, like if you are writing styles for a self-contained component — the component and it’s styles will be unique in the scope. Styling id’s is also explicit, since id’s are unique you know changing the styles won’t have any unintended side effects. Obviously this doesn’t mean I think all components should be individually styled with an id, there will be unique scenarios.. unless you’re an atomic css purist I guess.
3 likes Like Comment button
No, it’s not. You can’t use one id twice in case you want reuse your styles. If you write styles for component and want scoped css, you can use classes, not id’s.
Software dev specializing in privacy & infosec. Indie gamedev over enterprise. People over profit. ¯\_(ツ)_/¯. Basic income for all, direct democracy now. CBDC’s will END privacy.
You’re building a button component, self contained scoped css and shadow dom. There is no point in avoiding styling IDs. Using ID’s is explicit and its clear which element the style is applied to.
If all css is global because it may be reused at some point in the future, you’ll be swimming in an ocean of styles with fun side effects. Be explicit about reuse, minimize scope. The end.
Read my answer again. I didn’t say any word about global styling. You can achieve styling with classes, but styling an id is a bad tone. ID’s are good for querying elements in your scripts, but I see no reason in styling them.
Suppose you have two button components. They have similar styles but different background colors. Will you style each id or you create some common class for them and then extend it for different background color situations?
At the end of the day you can write styles as you want. But code practices will help you to maintain and write clean code.
Software dev specializing in privacy & infosec. Indie gamedev over enterprise. People over profit. ¯\_(ツ)_/¯. Basic income for all, direct democracy now. CBDC’s will END privacy.
If your css is scoped to a component it can’t be reused outside of that component without extracting it first, when extracted it’s scope will be global. Minimizing scope minimizes side effects and complexity. Enable reuse as needed. To be very clear, a component typically has VERY few styled id’s and its very specific. An element styled this way almost always have classes too. Example —>
That is never ever going to be reused. Style the ID, be explicit when you can. Its clear that this style is applied once, and to a specific clearly documented element.
The button element can be styled from outside the shadow dom, either using the ::part selector, css variables or element attributes. A button that is styleable from the outside increases its reuse potential at the cost of component complexity.
Having two buttons seems very strange, why would I ever have two button components? I would definitely not extend a simple button just to change its color.
Style reuse, being explicit and minimizing scope are code practices I’m trying to argue for. You never use the :host selector either?
I see your points and also I see lack of developer and ui/ux experience in your words. Sure, there will be situations when you need two or more buttons. Modal windows for example.
I would definitely not extend a simple button just to change its color.
Well, why? 😀 Oh yes, because you will copy/paste buttons and style them with ID’s.
:host is interesting but not popular selector, so no, I don’t use it everyday, especially when working with frameworks.
Software dev specializing in privacy & infosec. Indie gamedev over enterprise. People over profit. ¯\_(ツ)_/¯. Basic income for all, direct democracy now. CBDC’s will END privacy.
It seems you’re still misunderstanding me, I don’t use frameworks and build my own atoms — inputs, buttons, dialogs etc. When I say one button component, I mean one reusable component that can appear on a page more than once — a custom element, or a web component if you will. Creating a button component and instantiating it twice in a dialog is no problem, because the button itself has no embedded onclick logic — that is an event listener attached externally. Now creating two different button components would be strange, because a button is a button.. one styleable button will be enough.
I already explained how I will style the button. Three different methods that are standard ways of doing it when working with web components. None of those ways entails copy pasting, external styling can and will be reused to ensure the components appearance is uniform across the application.
Well you should have the same problem with :host as using id’s to style elements. And it’s hugely popular, in fact I’ve never seen a web component that didn’t use it. To clarify one final time, id’s are fine to use for styling components internally — no downstream consumer should extract css out of your component for reuse. If you have a component that appears once in your shadow dom, it’s fine to style by ID — for a few attributes that won’t ever be reused, like those in the given example.
Convert URL to PDF And Print Using JavaScript
To Convert URL to PDF And Print Using JavaScript, we can use hidden . Here we do a complete code example, where.
To Convert URL to PDF And Print Using JavaScript, we can use hidden .
Here we do a complete code example, where we will see how we can print an external URL as a PDF without opening it on the same page.
In web development sometimes we have to show some pages as PDF or download HTML pages as PDF via URL using JS.
This is the important concept of the conversion of URL to PDF by using JavaScript.
Here is the complete source code to Convert External URL to PDF And Print Using JavaScript,
Code Highlights:
- Here we create 3 functions, the first is for print window close operation, and the second is for events work on the print window
- And the last function (printPage(sURL)) is for creating a hidden iframe which is used to print or we can save it as a PDF.
- On printPage(sURL) the function we can define the style of the print PDF file.
- By using the same function we can manage the height, width, border, and alignment of the generated PDF for print.
- At last, we created a span (you can choose the button) where we call onclick() function to call the print function with URL as an argument.
How to Use
Copy the complete source code and paste it into your project.
Use onclick function to call the complete print PDF function with a button or text click.
Sometimes you get the CORS error which occurs because of different domains, so you have to first set the CORS permission on the URL that you want to print.
It is also helpful when you want to print a PDF file using JavaScript without opening it and print directly to the default printer.
I hope you get a complete understanding of the code.
Please let me know if you are facing any issues with the implementation.