简体   繁体   English

如何在 reactjs 中静默打印 PDF 文件?

[英]How to Print PDF file silently in reactjs?

const pdfURL = "someurl.com/document.pdf";
const handlePrint = (e: React.FormEvent) => {
        e.preventDefault();
        const win: Window | null = window.open(pdfURL);
        if (win) {
            win.onload = () => {
                win.print();
            };
        }
    };

above code opens PDF file into new tab and then print but I want to print directly without opening it into a new tab.上面的代码将 PDF 文件打开到新选项卡中然后打印,但我想直接打印而不将其打开到新选项卡中。

You can use the window.print() method to print a PDF file silently without opening it in a new tab.您可以使用 window.print() 方法静默打印 PDF 文件,而无需在新选项卡中打开它。

Here's an example of how you can use window.print() to print a PDF file in React:这是一个示例,说明如何在 React 中使用 window.print() 打印 PDF 文件:

import React from 'react';

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

const handlePrint = (e: React.FormEvent) => {
  e.preventDefault();

  // Open the PDF file in an iFrame
  const iFrame = document.createElement('iframe');
  iFrame.src = pdfURL;

  // Append the iFrame to the document
  document.body.appendChild(iFrame);

  // Wait for the iFrame to load, then print the PDF
  iFrame.onload = () => {
    window.print();
  };
};

const MyComponent = () => {
  return (
    <button onClick={handlePrint}>Print PDF</button>
  );
};

export default MyComponent;

This code will create an iframe element, load the PDF file into the iframe, and then print the PDF file when it finishes loading.此代码将创建一个 iframe 元素,将 PDF 文件加载到 iframe 中,然后在加载完成后打印 PDF 文件。

Note that this approach will only work if the PDF file is hosted on a server that allows cross-origin resource sharing (CORS).请注意,此方法仅在 PDF 文件托管在允许跨源资源共享 (CORS) 的服务器上时才有效。 If the PDF file is hosted on a server that does not allow CORS, you will need to use a different approach to print the PDF file silently.如果 PDF 文件托管在不允许 CORS 的服务器上,您将需要使用不同的方法静默打印 PDF 文件。

install npm package安装 npm package

npm install print-js --save

Add following code添加以下代码

import print from "print-js";

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

const handlePrint = (e: React.FormEvent) => {

    e.preventDefault();
    print(pdfURL);

};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM