我正在使用来自 https://mozilla.github.io/pdf.js/getting_started/#download 的 pdf.js (v3.10.111) 稳定版本(适用于现代浏览器)。
我能够加载 pdf 文件并对其进行图形修改,并将修改后的文件保存到我的桌面上。其代码如下:
。但是,我的目标是将文件保存回服务器。我不太清楚如何使用 Javascript / Jquery 获取修改后的文件的数据。我怎样才能做到这一点?
======
这是我当前的代码:
<!DOCTYPE html>
<html>
<head>
<script src="build/pdf.js"></script>
<script src="build/pdf.worker.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div id="pdf-container"></div>
<iframe id="pdf-js-viewer" src="web/viewer.html?file=a.pdf" title="webviewer" frameborder="0" width="1024" height="1024"></iframe>
<button id="downloadPdfButton">Download PDF</button>
<div id="pdf-data-container"></div> <!-- The <div> to display the PDF binary data -->
<script type="text/javascript">
$(document).ready(function () {
let pdfDocument = null;
let editedPdfData = null; // To store edited PDF data
const pdfUrl = 'a.pdf';
pdfjsLib.getDocument(pdfUrl).promise.then(function (pdfDoc) {
pdfDocument = pdfDoc;
$('#downloadPdfButton').click(function () {
if (pdfDocument) {
// Check if editedPdfData is available, if not, use the original PDF data
if (editedPdfData) {
// Use the edited PDF data
displayEditedPdfData();
} else {
// Get the PDF blob data
pdfDocument.getData().then(function (data) {
// Create a Blob from the binary PDF data
const pdfBlob = new Blob([data], { type: 'application/pdf' });
// Create a URL for the Blob
const pdfUrl = URL.createObjectURL(pdfBlob);
// Display the original PDF binary data in the div
displayPdfData(pdfUrl);
});
}
} else {
alert('PDF not loaded.');
}
});
});
// Function to display PDF data in the div
function displayPdfData(dataUrl) {
const pdfDataContainer = document.getElementById('pdf-data-container');
pdfDataContainer.innerHTML = `<object data="${dataUrl}" type="application/pdf" width="100%" height="600px"></object>`;
}
// Function to display edited PDF data in the div
function displayEditedPdfData() {
if (editedPdfData) {
// Create a Blob from the edited PDF data
const editedPdfBlob = new Blob([editedPdfData], { type: 'application/pdf' });
// Create a URL for the Blob
const editedPdfUrl = URL.createObjectURL(editedPdfBlob);
// Display the edited PDF binary data in the div
displayPdfData(editedPdfUrl);
}
}
});
</script>
</body>
</html>
======
这几乎是好的。唯一的问题是它显示原始 pdf,而不是编辑后的 pdf。我想在 div 中显示编辑后的 pdf。我想获取二进制数据。
用于将 pdf 文件保存到服务器。
async function saveData(){
const formdata = new FormData();
const data = await PDFViewerApplication.pdfDocument.saveDocument();
const blob = new Blob([data], {type: "application/pdf"});
formdata.append('userfile', blob, 'filename.pdf');
await fetch('save', {
method: 'POST',
body: formdata
})
.then(response => {
if(response.redirected){
// Statements...
return false;
}else{
return response.json();
}
})
.then(data => {
if(data !== false){
if(data.status == 'ok'){
// Statements...
}else{
throw new Error('Error');
}
}
})
.catch(error => {
// Statements...
});
}