簡體   English   中英

如何使用 IText 在特定 xy 坐標處將圖像添加到 PDF?

[英]How can I add an image to a PDF at specific x-y coordinates using IText?

我有現有的 PDF,需要動態添加圖像/圖像。 圖片來自文件上傳。 上傳文件后,如何指定在 PDF 上放置圖像的位置。 我發現的一個代碼片段無法正常工作。 這需要適用於具有任意頁數的 PDF。 據我了解,絕對定位是從PDF最后一頁的左下角設置的。 如果我需要在第 1 頁頂部和左側 50 像素處顯示圖像,我該如何實現? 或者,如果我需要在第 2 頁上顯示距頂部 50 像素/距左側 100 像素的圖像?

我嘗試使用在http://rip747.wordpress.com/2009/03/26/add-an-image-dynamically-to-a-pdf-with-cf-and-itext/找到的代碼。 我已根據以下需要對其進行了修改:

<cfscript>
    myLeft = 30;
    myTop = 50;
    myPageNum = 1;

    // output buffer to write PDF
    fileIO = createObject("java","java.io.FileOutputStream").init(myOutputPath);

    // reader to read our PDF
    reader = createObject("java","com.lowagie.text.pdf.PdfReader").init(mySourcePath);

    // stamper so we can modify our existing PDF
    stamper = createObject("java","com.lowagie.text.pdf.PdfStamper").init(reader, fileIO);

    // get the content of our existing PDF
    content = stamper.getOverContent(reader.getNumberOfPages());

    // create an image object so we can add our dynamic image to our PDF
    image = createobject("java", "com.lowagie.text.Image");

    // initalize our image
    img = image.getInstance(imgPath);

    x = (reader.getPageSize(1).width() - img.scaledWidth()) - myLeft;
    y = (reader.getPageSize(1).height() - img.scaledHeight()) - myTop;

    // now we assign the position to our image
    img.setAbsolutePosition(javacast("float", x), javacast("float", y));

    // add our image to the existing PDF
    content.addImage(img);

    // flattern our form so our values show
    stamper.setFormFlattening(true);

    // close the stamper and output our new PDF
    stamper.close();

    // close the reader
    reader.close();
</cfscript>

上面的代碼將我的圖像放在第 2 頁的右上角 - 距左上角 50px/30px。

我知道我很接近......只需要一點幫助來確定我的需要。

我已經更新了我的代碼。 這會將圖像帶到第 2 頁的左上角 - 正確定位,但我希望它在第 1 頁:

x = myLeft;
y = (reader.getPageSize(1).height()) - img.scaledHeight() - myTop;

我想也許我需要添加第 1 頁的高度才能使圖像達到第 1 頁,但是當我嘗試以下任一選項時,圖像會完全消失:

// I figure I'll need something like this to handle multi-page docs
y = (reader.getPageSize(1).height() * reader.getNumberOfPages()) - img.scaledHeight() - myTop;

y = reader.getPageSize(1).height() + reader.getPageSize(1).height() - img.scaledHeight() - myTop;

你從stamper.getOverContent(reader.getNumberOfPages());得到你的“OverContent”。 . getOverContent()的參數是頁碼。 因此,您的代碼正在獲取最后一頁的PdfContentByte ,而不是第一頁。

我找到了答案:

頁碼必須在com.lowagie.text.pdf.PdfStamper.getOverContent()中設置:

content = stamper.getOverContent(myPageNum);

知道這很容易。

你用的是CF8+嗎? 您可以使用

<cfpdf action="addWatermark" source="myPDF.pdf" image="myImage.jpg" 
       position="0,0" rotation="0" showOnPrint="true" opacity="10">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM