我正在制作一個需要從特定 div 生成 pdf 的反應應用程式。
當前情景:
-> 制作了一個帶有可列印 div 的應用程式,單擊按鈕后,會生成并下載 pdf。
代碼:
<div id="printable-div">
<h1>Generate PDF</h1>
<p>Create a screenshot from this div, and make it as a PDF file.</p>
<p style={{ color: "red" }}>
*Then do not download instead attach to contact us form as attachment.
</p>
</div>
<button id="print" onClick={printPDF}>
Contact Us
</button>
列印PDF功能:
const printPDF = () => {
setIsShowContact(true);
const domElement = document.getElementById("printable-div");
html2canvas(domElement).then((canvas) => {
const doc = new jsPdf();
doc.save(`attachment.pdf`);
});
};
單擊“聯系我們”按鈕后,會發生兩個操作。
-> Pdf 檔案已下載。
-> 帶有輸入的表單Name,Email并將Attachment顯示。
作業密碼箱:
要求:
這里的要求是單擊“聯系我們”按鈕,應該生成 pdf 但不可下載,而是需要將生成的 pdf 附加到input type="file"聯系人中form。
我們需要id="printable-div" 在單擊聯系按鈕時將特定 div 中的資料用戶資訊作為 pdf 附件發送到后端 api。
在實際應用中,這就像對產品的查詢,用戶選擇具有某些配置的產品,最后將根據他們選擇的配置向用戶顯示產品資訊。然后用戶將單擊“聯系我們”按鈕,因此
printable-div將獲得用戶搜索的產品資訊,因此我們需要將其捕獲為 pdf 并附加到輸入并在表單提交時發送到后端。
請幫助我輸入有關實作將生成的 pdf 作為附件附加到輸入欄位的場景的輸入。
uj5u.com熱心網友回復:
問題
1.您需要正確轉換PDF,雖然目的是在輸入欄位中附加PDF,但您下載的是空白PDF。
第一步是正確下載 PDF,參考 id 為 printable-div 的 DIV 元素,然后,而不是下載,將其附加到輸入欄位。
無效代碼在這里:
const printPDF = () => {
setIsShowContact(true);
const domElement = document.getElementById("printable-div");
html2canvas(domElement).then((canvas) => {
const doc = new jsPdf(); <<- YOU`RE CREATING AN EMPTY PDF AND
doc.save('attachment.pdf'); <<- DOWNLOADING THIS EMPTY PDF
});
};
解決方法很簡單,只需使用
canvas傳遞給callback函式的引數而不是生成新的PDF
2.您需要附加 .files 屬性而不是添加
相反,生成 pdf 需要
附加到input type="file"聯系人中form。
無法向屬于 FileList 類的.filesofinput[type="file"]欄位添加新專案,另一方面,可以對其進行更改,即洗掉舊的 FileList 并附加一個帶有必要檔案的新檔案。
在此示例中,它只是一個檔案。
解決方案
1.您需要將作為回呼傳遞的畫布從html2canvas函式轉換為檔案。
您可以通過以下方式執行此操作:
const canvas2file = (canvas, fileName = 't.jpg') =>
new Promise(resolve => {
canvas.toBlob((blob) => {
resolve(new File([blob], fileName, { type: "image/jpeg" }))
}, 'image/jpeg');
})
2、你需要在函式所期望的promisehtml2canvas中使用這個函式,即:
html2canvas(domElement)
.then(canvas2file)
3.您需要獲取型別為檔案的輸入欄位的參考(或document.querySelector/ document.getElementXXX),以及之前轉換的檔案本身的狀態變數(通過 canvas2file 函式),即:
function App() {
...
const fileRef = useRef(); //Reference to input[type="file"]
const [file, setFile] = useState(); //State variable that contains the File
...
}
4.修改printPDF函式保存File到狀態變數
const printPDF = () => {
setIsShowContact(true);
const domElement = document.getElementById("printable-div");
html2canvas(domElement)
.then(canvas2file)
.then(setFile);
};
5、使用useEffect鉤子檢測File狀態變數中的變化,即用戶每次點擊“聯系我們”,File都會通過canvas2file函式生成一個新的,并將這個檔案存放在檔案狀態變數中.
檢測到此更改后,我們從 input[type="file"] 中洗掉 .files(型別為 FileList),然后將新的 FileList 重新附加到輸入,例如:
useEffect(() => {
if(!fileRef.current) return;
let list = new DataTransfer();
list.items.add(file);
fileRef.current.files = list.files;
console.log(fileRef.current)
}, [file])
編碼
const { useEffect, useRef, useState } = React;
const canvas2file = (canvas, fileName = 't.jpg') =>
new Promise(resolve => {
canvas.toBlob((blob) => {
resolve(new File([blob], fileName, { type: "image/jpeg" }))
}, 'image/jpeg');
})
function App() {
const [isShowContact, setIsShowContact] = useState(false);
const fileRef = useRef();
const [file, setFile] = useState();
useEffect(() => {
if(!fileRef.current) return;
let list = new DataTransfer();
list.items.add(file);
fileRef.current.files = list.files;
console.log(fileRef.current)
}, [file])
const printPDF = () => {
setIsShowContact(true);
const domElement = document.getElementById("printable-div");
html2canvas(domElement)
.then(canvas2file)
.then(setFile);
};
return (
<div className="App">
<div id="printable-div">
<h1>Generate PDF</h1>
<p>Create a screenshot from this div, and make it as a PDF file.</p>
<p style={{ color: "red" }}>
*Then do not download instead attach to contact us form as attachment.
</p>
</div>
<br />
<button id="print" onClick={printPDF}>
Contact Us
</button>
<br />
<br />
<br />
{isShowContact && (
<form>
<div id="contact">
<div className="block">
<label>Name:</label>
<input type="text" defaultValue="John Doe" />
</div>
<br />
<div className="block">
<label>Email:</label>
<input type="email" defaultValue="[email protected]" />
</div>
<br />
<div className="block">
<label>Table pdf as attachment:</label>
<input ref={fileRef} type="file" />
</div>
</div>
</form>
)}
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
label {
display: inline-block;
width: 75x;
text-align: right;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<script src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<title>React App</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
嘗試這個
由于 Stackoverflow 沙盒策略,上面的代碼可能不會運行,因此我將作業代碼托管在 Codesandbox 上。
演示網址:https ://codesandbox.io/s/html2canvas-jspdf-forked-5ennvt?file=/src/index.js
uj5u.com熱心網友回復:
不幸的是,您無法設定檔案輸入的值,即使您自己給它一個“檔案”。在添加附件時,您必須攔截表單提交并構建您自己的請求。FormData API對此很有用。
這是更新沙箱的鏈接: https
://codesandbox.io/s/html2canvas-jspdf-forked-eun59q?file=/src/
index.js 這里是使用的 jsPDF 函式檔案:https://artskydj.github。 io/jsPDF/docs/jsPDF.html#output
uj5u.com熱心網友回復:
據我了解,您實際上是在嘗試截取某個區域的螢屏截圖并將其以表單資料的形式發送。
您可以使用一個名為use-react-screenshot. 它非常容易實作,您需要使用createRefreact 中的鉤子設定參考區域。
獲得螢屏截圖后,您可以將其與表單資料一起靜默上傳到資料庫的某個位置,以便在查看表單資料時參考螢屏截圖。
使用當前方法,我認為沒有辦法以編程方式設定檔案輸入。
我希望這有幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/521468.html
標籤:javascript反应pdfjspdfhtml2canvas
