簡體   English   中英

C#.NET核心使用ITextSharp向現有PDF添加具有透明度的圖像

[英]c# .NET CORE adding image with transparency to existing PDF using ITextSharp

我的目標是在現有pdf(而非水印)的每一頁上添加公司徽標。

由於pdf文件和徽標的特殊性,我只能將徽標放在pdf內容的頂部(而不是其下方),並且徽標必須支持透明性。

另一個限制是我必須使用.NET Core。

發布此答案,因為我找不到明確的解決方案。 歡迎提出建議/更正/改進。

希望有人覺得這有用。

支持.NET Core的最新iTextSharp庫是iText7,但是我不能合法地使用它。 對我來說,既不使我的代碼開源,也不選擇購買許可證。 因此,我使用舊的第三方庫:

Install-Package iTextSharp.LGPLv2.Core

我正在使用的最新版本是1.3.2。

需要以下用途

using System;
using System.Drawing.Imaging;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;

為了使圖像具有pdf透明度,必須以正確的格式打開圖像

var preImage = System.Drawing.Image.FromFile(imagePath);
var image = Image.GetInstance(preImage, ImageFormat.Png);

添加圖像時,不要選擇內嵌圖像也很重要

canvas.AddImage(image);//do not put .AddImage(image, true);

這是所有代碼

var imagePath = "logo.png";
var pdfPath = "edit_this.pdf";

//load pdf file
var pdfBytes = File.ReadAllBytes(pdfPath);
var oldFile = new PdfReader(pdfBytes);

//load image
var preImage = System.Drawing.Image.FromFile(imagePath);
var image = Image.GetInstance(preImage, ImageFormat.Png);
preImage.Dispose();

//optional: if image is wider than the page, scale down the image to fit the page
var sizeWithRotation = oldFile.GetPageSizeWithRotation(1);
if (image.Width > sizeWithRotation.Width)
    image.ScalePercent(sizeWithRotation.Width / image.Width * 100);

//set image position in top left corner
//in pdf files, cooridinates start in the left bottom corner
image.SetAbsolutePosition(0, sizeWithRotation.Height - image.ScaledHeight);

//in production, I use MemoryStream
//I put FileStream here to test the code in console application
using (var newFileStream = new FileStream("with_logo.pdf", FileMode.Create))
{
    //setup PdfStamper
    var stamper = new PdfStamper(oldFile, newFileStream);

    //iterate through the pages in the original file
    for (var i = 1; i <= oldFile.NumberOfPages; i++)
    {
        //get canvas for current page
        var canvas = stamper.GetOverContent(i);
        //add image with pre-set position and size
        canvas.AddImage(image);
    }

    stamper.Close();
}

此代碼適用於本地文件。 在我的現實世界中,我收到作為Base64字符串的pdf文件,從本地存儲中添加徽標,將其轉換回Base64字符串,並將其輸出到網頁上。

我強制(硬編碼)以PNG格式打開圖片,因為我可以控制徽標的擴展名。 如有必要,您可以動態設置圖像格式。

暫無
暫無

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

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