DEV Community

Alin Climente
Alin Climente

Posted on • Updated on

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;
}

Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Here is a basic html:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Add here the styles and script we described up -->
    <title>This will be the title of the pdf file</title>
</head>

<body id="container">

    <a href="#" id="print">GENERATE PDF!</a>

    <h1>Super cool custom pdf</h1>

    <p>This pdf is generated from the client side without any external libraries!</p>

</body>

</html>

Enter fullscreen mode Exit fullscreen mode

And... that's it!

Here is how what we did up will work:

generate-pdf-gif

Latest comments (41)

Collapse
 
sachadee profile image
SachaDee

Excellent post !!Easy way to generate a PDF and save it where you want!

Collapse
 
shashamura profile image
Shashamura1

I really have interest in dev is all about Education to build your self to be self development to be self independent fainacialy and Educatinaly..I am getting improve with all what I am reading in here dev.com

Collapse
 
webjoyable profile image
webjoyable

If it was window.pdf() it would be a neat post, otherwise it's a clickbait

 
defite profile image
Nikita Makhov

Now I see. It's all about web components, which I don't use at all.

 
defite profile image
Nikita Makhov • Edited

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? :D 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.

 
defite profile image
Nikita Makhov

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.

Collapse
 
defite profile image
Nikita Makhov

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.

Collapse
 
shifi profile image
Shifa Ur Rehman

I sincerely implore people to do constructive criticism. You only add injury to the salt. The only problem with my dude was that... He is bad at keyword research like you dinosaurs here. Chill. Relax. Get that fixed and if he doesn't do that, go ahead and yell at him for whatever reason. But for God's sake, don't make this toxic for everyone else. I come here for comments more than the articles. Learn much much more that way. If you have nothing good to say, better shut up.

Collapse
 
bencun profile image
bencun

This low quality, low effort content is killing me.

Collapse
 
climentea profile image
Alin Climente

Welcome to dev.to!

Collapse
 
thi3rry profile image
Thierry Poinot

The solution you provide in your article need a browser that supports to print a page into a pdf file. You have a macos device it's ok. You are on mobile, it's not ok.
Your solution juste provide a button to trigger the print action AND to hide this button on the printed version of this page. There is nothing to deals with PDF.

Collapse
 
climentea profile image
Alin Climente

Damn... Indeed on mobile browsers this doesn't work.

Collapse
 
gitkat profile image
GitKat

"How to save HTML Page into PDF file"

Collapse
 
itsdonnix profile image
Don Alfons • Edited

I did the same thing using puppeteer and end EJS to generate PDF.
Also with pdflib to change the title of the document.

Checkout on gist ->
gist.github.com/donnisnoni/a9fdf25...

Collapse
 
climentea profile image
Alin Climente

You need a backend for that.

Collapse
 
zodman profile image
Andres 🐍 in 🇨🇦 • Edited

and here when the client said! Nooo I want download the pdf file, not print it!

and now you understand its better implement wkhtmltopdf instead of explain.

Collapse
 
climentea profile image
Alin Climente

You need a backend for that. Sometimes this simple things will do the job.

Collapse
 
siddharthdb profile image
Siddharth B

Dear Author,
This article falls in the grey area of click bait based on the title of the article. I would suggest to put some effort in writing a well thought out article by researching on the topic.

For others who felt betrayed by the title, here are some pointers
medium.com/@ayusharma.in/generate-...
bannerbear.com/blog/how-to-convert...

Collapse
 
climentea profile image
Alin Climente

You need a backend for that.

Collapse
 
poopa profile image
poopa

wrong title