2020-06-30
iTextSharp 5 的新版改名為 iText 7 了。
Visual Studio 2019 v16.6.2 + WebForm + ASP.NET
NuGet 安裝 iText 7.1
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="iText7ReplaceTextinPDF.Default" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /> </div> <asp:Label ID="Label1" runat="server" ></asp:Label> </form> </body> </html> |
Default.aspx.cs
using System; using System.IO;
using System.Text;
using iText.Kernel.Pdf;
namespace iText7ReplaceTextinPDF
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string source = @"C:\TEMP\testt.pdf";
string dest = @"C:\TEMP\testt2.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfReader(source), new PdfWriter(dest));
PdfPage page = pdfDoc.GetFirstPage();
PdfDictionary dict = page.GetPdfObject();
PdfObject pdfObject = dict.Get(PdfName.Contents);
if (pdfObject is PdfStream )
{
PdfStream stream = (PdfStream)pdfObject;
byte[] data = stream.GetBytes();
String replacedData = iText.IO.Util.JavaUtil.GetStringForBytes(data).Replace("@", "###");
stream.SetData((Encoding.UTF8.GetBytes(replacedData)));
}
pdfDoc.Close();
}
}
}
|
實際測試無效,字串沒有被換掉。
debug 發現 if (pdfObject is PdfStream ) 有問題,pdfObject 是 PdfArray,不是 PdfStream。
但是另外自己用Word編寫一個.docx,只有單純的文字,另存成.pdf,測試發現 pdfObject 是 pdfStream,但是依然字串沒有被換掉。
(完)
(完)
相關
Replacing PDF objects
iTextSharp Replace Text in existing PDF without loosing formation [duplicate]
Replace text in PDF file using iTextSharp(not AcroFields) [closed]
沒有留言:
張貼留言