简体   繁体   English

pdf-lib:无法在扫描的 pdf 中绘制文本

[英]pdf-lib: Not able to draw text in a scanned pdf

I'm trying to draw text in a rectangle a pdf using the pdf-lib library.我正在尝试使用 pdf-lib 库在矩形 pdf 中绘制文本。 It is possible for pdf files that are not scanned.未扫描的 pdf 文件是可能的。 See below screenshot:请看下面的截图:

矩形文本 - 普通 pdf 文件

It doesn't work for scanned pdf files.它不适用于扫描的 pdf 文件。 Basically it's the modifyPdf function that does the job.基本上它是完成这项工作的modifyPdf函数。 We read the pdf file and then draw the rectangle and text.我们读取pdf文件,然后绘制矩形和文本。 Then we encode it using base64 and set it as the iframe source.然后我们使用 base64 对其进行编码并将其设置为 iframe 源。 Please see below code:请看下面的代码:

<?php
if(isset($_GET['fname']))
{
    $fname = trim($_GET['fname']);
    $fname_array = explode('/', $fname);
    $label_str = end($fname_array);
    $label_str = addslashes($label_str);
}
else
    die('Access denied');
?>
<html>
<head>
    <meta charset="utf-8" />
    <title>PDF Viewer</title>
</head>

<body></body>

 <!--<script src="js/pdf-lib.min.js"></script>-->
 <script src="https://unpkg.com/pdf-lib@1.11.1/dist/pdf-lib.js"></script>


<!-- <script src="https://unpkg.com/pdf-lib@1.4.0"></script>
    <script src="https://unpkg.com/downloadjs@1.4.7"></script> -->

<script>

    (async () => {


    //const { degrees, PDFDocument, rgb, StandardFonts } = PDFLib

    let FinalModifiedFilesToBeUploaded = await modifyPdf('<?=$label_str?>', 13, '<?=$fname?>')

    for (let i = 0; i < FinalModifiedFilesToBeUploaded.length; i++) {
        let iframeSrc = FinalModifiedFilesToBeUploaded[i]
        let iframe = document.createElement('iframe')
        iframe.setAttribute('style', 'width: 100%; height: 100%;')
        iframe.setAttribute('src', iframeSrc)
        iframe.setAttribute('class', 'custom-pdf-frame')
        document.body.appendChild(iframe)
    }

    async function modifyPdf(text, textSize, path ) {
        let MODIFIED_FILES = []
      // Fetch an existing PDF document
      /*const url = 'https://pdf-lib.js.org/assets/with_update_sections.pdf'*/
      const url = path
        const existingPdfBytes = await fetch(url).then(res => res.arrayBuffer())

      const pdfDoc = await PDFLib.PDFDocument.load(existingPdfBytes)
                        const helveticaFont = await pdfDoc.embedFont(PDFLib.StandardFonts.Helvetica)
                        const textWidth = helveticaFont.widthOfTextAtSize(text, textSize);
                        // const textHeight = helveticaFont.heightAtSize(textSize);
                        const pages = pdfDoc.getPages()
                        const firstPage = pages[0]
                        console.log(firstPage)
                        if (firstPage) {
                            const {
                                width,
                                height
                            } = firstPage.getSize()
                            try{
                            console.log(firstPage.drawText(text, {
                                x: width / 2 - textWidth / 2,
                                y: height / 2 + 367,
                                size: textSize,
                                font: helveticaFont,
                                opacity: 1,
                                //color: PDFLib.rgb(0.13333333333333333, 0.5450980392156862, 0.13333333333333333),
                            }))
                            }
                            catch(err) {
  alert('test1'+err)
}
try{
                            firstPage.drawRectangle({
                                x: width / 2 - textWidth / 2 - 10,
                                y: height / 2 + 357,
                                width: textWidth + 20,
                                height: 30,
                                borderWidth: 1,
                                //color: PDFLib.rgb(1, 1, 0),
                                opacity: 0.2,
                            })
}
catch(err) {
  alert('test2'+err)
}
                            const pdfDataUri = await pdfDoc.saveAsBase64({
                                dataUri: true
                            });
                            MODIFIED_FILES.push(pdfDataUri)
                        } else {
                            alert('Page not found')
                        }
console.log(MODIFIED_FILES)
                        return MODIFIED_FILES

            // Trigger the browser to download the PDF document
      //download(pdfBytes, "pdf-lib_modification_example.pdf", "application/pdf");
    }
    })()
</script>

</html>

I think I found out the answer.我想我找到了答案。 I identified that for scanned files the text was indeed getting printed but on areas out of the scope of display.我发现对于扫描的文件,文本确实被打印出来,但在显示范围之外的区域。 This was because the width of the document was greater than the height.这是因为文档的宽度大于高度。 So I fixed it using the following code:所以我使用以下代码修复了它:

if(width > height)
                            {
                                try{
                            firstPage.drawText(text, {
                                x: height+150,
                                y: width-430,
                                size: textSize,
                                font: helveticaFont,
                                opacity: 1,
                                color: PDFLib.rgb(0.13333333333333333, 0.5450980392156862, 0.13333333333333333),
                                rotate: PDFLib.degrees(-90),
                            })
                            }
                            catch(err) {
}
try{
                            firstPage.drawRectangle({
                                x: height+140,
                                y: width-420,
                                width: textWidth + 20,
                                height: 30,
                                borderWidth: 1,
                                color: PDFLib.rgb(1, 1, 0),
                                opacity: 0.2,
                                rotate: PDFLib.degrees(-90),
                            })
}
catch(err) {
}
                            }
                            else
                            {
                                firstPage.drawText(text, {
                                x: width / 2 - textWidth / 2,
                                y: height / 2 + 367,
                                size: textSize,
                                font: helveticaFont,
                                opacity: 1,
                                color: PDFLib.rgb(0.13333333333333333, 0.5450980392156862, 0.13333333333333333),
                            })
                            firstPage.drawRectangle({
                                x: width / 2 - textWidth / 2 - 10,
                                y: height / 2 + 357,
                                width: textWidth + 20,
                                height: 30,
                                borderWidth: 1,
                                color: PDFLib.rgb(1, 1, 0),
                                opacity: 0.2,
                            })
                            }

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

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