为了在我的React应用程序中实现PDF-LIB功能,我正在尝试使用PDF。其目的是呈现PDF版本的表单,并允许用户编辑字段,然后保存其进度。
出于这个原因,我决定使用PDF-LIB,而不是像react-pdf这样的替代方案,因为这似乎是最健壮的。
我对使用Fetch PDF & convert to byte array的过程的理解如下:Load PDF data and make changes --> Save updated PDF as byte array
我正在尝试改编here发现的示例
下面是我的代码:
const LoadPDF = () => {
const [pdfInfo, setPdfInfo] = useState([]);
useEffect(() => {
modifyPdf();
}, []);
const modifyPdf = async () => {
const existingPdfBytes = await fetch(
"https://pdf-lib.js.org/assets/with_update_sections.pdf"
).then((res) => res.arrayBuffer());
const pdfDoc = await PDFDocument.load(existingPdfBytes);
const helveticaFont = await pdfDoc.embedFont(StandardFonts.Helvetica);
const pages = pdfDoc.getPages();
const firstPage = pages[0];
// Get the width and height of the first page
const { width, height } = firstPage.getSize();
firstPage.drawText("This text was added with JavaScript!", {
x: 5,
y: height / 2 + 300,
size: 50,
font: helveticaFont,
color: rgb(0.95, 0.1, 0.1),
rotate: degrees(-45),
});
const pdfBytes = await pdfDoc.save();
const docUrl = URL.createObjectURL(
new Blob(pdfBytes, { type: "application/pdf" })
);
setPdfInfo(docUrl);
};
return (
<>{<iframe title="test-frame" src={pdfInfo} type="application/pdf" />}</>
);
};
export default LoadPDF;文档表明我应该能够在iframe中呈现PDF。我尝试创建一个iframe元素并将其从modifypdf函数返回。我还尝试将修改后的PDF数据设置为pdfInfo in状态。我尝试的第三件事是创建一个图像,然后渲染它。
在这一点上,我迷路了。如果我希望用户能够编辑文档并能够保存,那么在iFrame中呈现PDF对我来说是最好的选择吗?在获取所需格式的数据和将其呈现到屏幕之间,我有一个脱节。我知道我需要重构这个库,但我正在尝试了解这个库是如何工作的,然后致力于解决我问题的其他部分。
9/29/20更新:
我意识到我有一个字节数组,其中包含const pdfBytes = await pdfDoc.save();带来的PDF修订版,所以我使用URL.createObjectURL将数据转换为一个URL,以便在呈现iframe时可以在源代码中使用。该部分不再中断,但PDF仍然不会在iframe中呈现。
我已经包含了上面编辑过的代码。
发布于 2021-04-02 23:08:18
添加这些行似乎可以为我修复代码:
var bytes = new Uint8Array(pdfBytes);
var blob = new Blob([bytes], { type: "application/pdf" });
const docUrl = URL.createObjectURL(blob);
setPdfInfo(docUrl);发布于 2021-03-29 20:00:31
我所做的和工作的:我添加了一个对iframe实例的引用:
import React, { useState, useEffect, useRef } from 'react';
const LoadPDF = () => {
...
const viewer = useRef(null);
const modifyPDF = async () => {
...
};
return (
<>{<iframe title="test-frame" src={pdfInfo} ref={viewer} type="application/pdf" />}</>
);
}发布于 2021-10-19 03:45:51
您需要做的就是将pdfBytes作为数组传递
const docUrl = URL.createObjectURL(new Blob([pdfBytes], {type: 'application/pdf'}))
setPdfInfo(docUrl);https://stackoverflow.com/questions/64111624
复制相似问题