javascript - 为每一页在 PDF 的侧面写下文本
问题描述
我使用pdflib
它,它非常适合我。但我无法让它在 PDF 的所有页面上写一条消息。
我怎样才能做到这一点,如果我上传 7 页 PDF,消息会出现在所有 7 页上。如果我上传 5 页 PDF,它会出现在所有 5 页上。
我尝试使用if
但最终没有得到它。
<script>
const {
degrees,
PDFDocument,
rgb,
StandardFonts
} = PDFLib
modifyPdf();
async function modifyPdf() {
// Fetch an existing PDF document
const url = '<?php echo $pdf;?>'
const existingPdfBytes = await fetch(url).then(res => res.arrayBuffer())
// Load a PDFDocument from the existing PDF bytes
const pdfDoc = await PDFDocument.load(existingPdfBytes)
// Embed the Helvetica font
const helveticaFont = await pdfDoc.embedFont(StandardFonts.Helvetica)
// Get the first page of the document
const pages = pdfDoc.getPages()
const firstPage = pages[0]
// Get the width and height of the first page
const {
width,
height
} = firstPage.getSize()
// Draw a string of text diagonally across the first page
firstPage.drawText('Firmado por <?php echo $usuarionombre;?>, en fecha <?php echo $fechafirma;?>!', {
x: 12,
y: height / 2 - 300,
size: 12,
font: helveticaFont,
color: rgb(0.95, 0.1, 0.1),
rotate: degrees(90),
//original ajustes.
// x: 5,
//y: height / 2 + 300,
//size: 12,
//font: helveticaFont,
//color: rgb(0.95, 0.1, 0.1),
//rotate: degrees(-90),
})
// Serialize the PDFDocument to bytes (a Uint8Array)
const pdfBytes = await pdfDoc.save()
// esto es para descargar el pdf
//download(pdfBytes, "pdf-lib_modification_example.pdf", "application/pdf");
// This step is only necessary if you don't already have a Buffer Object
var blob = new Blob([pdfBytes])
var reader = new FileReader();
reader.onload = function(event) {
var base64 = event.target.result
var res = base64.replace("data:application/octet-stream;base64,", "");
var sites = ['data:application/pdf;base64, ' + res]
document.getElementById('myIframe').src = sites[Math.floor(Math.random() * sites.length)];
};
reader.readAsDataURL(blob);
}
</script>
解决方案
不确定它是否是您尝试在所有页面上编写的“对角线消息”,但如果是这样,const firstPage = pages[0]
您应该迭代所有页面pages
以drawText()
在每个页面上使用,而不是只获取第一页。
// Get document pages
const pages = pdfDoc.getPages()
// Iterate every pages
pages.forEach(page => {
// Get the width and height of the page
const {
width,
height
} = page.getSize()
// Draw a string of text diagonally across the page
page.drawText('Firmado por <?php echo $usuarionombre;?>, en fecha <?php echo $fechafirma;?>!', {
x: 12,
y: height / 2 - 300,
size: 12,
font: helveticaFont,
color: rgb(0.95, 0.1, 0.1),
rotate: degrees(90),
})
})
推荐阅读
- karate - 关于空手道 UI 测试自动化,我如何在使用 karate-chrome 时上传文件?
- r - 如何在字符向量列表上使用 seqinr::computePI
- flutter - 检测 Scrollable 小部件是手动滚动还是以编程方式滚动
- android-studio - 如何在 Android Studio 4.1 中恢复构建窗口
- javascript - JavaScript 中是否有 Array.Sort 的快捷方式?
- sql - 添加列号的查询结果自动动态递增
- node.js - 从 sequelize.js 获取错误的对象名称包含从数据到数据的 JSON 响应中的方法
- xml - VS Code Salesforce 导入选项列表值 [isActive 标签缺失]
- python - 如何在 Python 中使用 API 密钥从 API 获取数据
- testing - Nodemon 忽略失败的命令