Silently print a PDF file using javascript
Asked Answered
P

1

6

The thing I want to build is that by clicking a button I want to trigger the direct print of a PDF file, but without opening or viewing it.

I have PDF as blob file returned from fetch API.

I tried a lot of examples but don't know exactly how to do it

Some examples tried:

// In my case, I had only blobData from PDF, but you can ignore this and set fileURL directly if it is not yours.
const file = new Blob([blobData], { type: 'application/pdf' });
const fileURL = window.URL.createObjectURL(file);

// As the URL is dynamic, we must set src here, but if it's not, just leave it direct on the HTML. 
// Also, be careful with React literals. If you do this in a <iframe> defined in JSX, it won't work 
// as React will keep src property undefined.
window.frames["my-frame"].src = fileURL;

// Then print:
window.frames["my-frame"].print();
<iframe name="my-frame" id="my-frame" title="my-frame" style="display: none"></iframe>

Also tried library, Print.js: http://printjs.crabbly.com/.

Is there way to print the pdf without visually opening it to the user? We should support only Chrome browser.

Can someone provide example how to do it in React, Redux application?

Purington answered 30/11, 2017 at 9:25 Comment(8)
Check if this is helpful - #30135887. it has github link to the code files check them as well.Inobservance
Thanks, i will try.Purington
This won't work for me, it kinda should look like this example stackoverflow.com/questions/46125045Purington
Why this more than weird requirement of not showing the pdf? As a user, I always want to see what I'll print, you're not going to make me print a 500 colored pages comic. Toner is not cheap.Mont
It is a requirement and user that uses this app knows what he is printing ant PDF file contains only one page.Purington
@Purington , did you resolved silently print issue?Martelli
@Mont If there's a list of files to print and you don't want user to confirm every print popupAnorak
@Anorak then merge in a single multi page pdf.Mont
A
1

try this print-js and this is npm package

install npm package

npm install print-js --save

Add following code

import print from "print-js";

const fileURL = "someurl.com/document.pdf"; 

const handlePrint = (e) => {

    e.preventDefault();
    print(fileURL);

};

similar question is here

Atahualpa answered 3/1, 2023 at 19:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.