I am currently trying to replace a placeholder text in a pdf using itext7.
I managed to get it working using this code:
PdfReader reader = new PdfReader(templatePath);
using (PdfDocument pdfDoc = new(reader, new PdfWriter(destinationPath)))
{
PdfPage page = pdfDoc.GetFirstPage();
PdfDictionary dict = page.GetPdfObject();
PdfStream contents = dict.GetAsStream(PdfName.Contents);
var bytes = reader.ReadStreamBytes(contents, true);
var pdfContents = Encoding.UTF8.GetString(bytes);
pdfContents = pdfContents.Replace("[(S)14(N)-5(O)]", $"[({modelData.CertificateNo})]");
pdfContents = pdfContents.Replace("[(O)93(W)81(N)]", $"[({modelData.Name})]");
pdfContents = pdfContents.Replace("[(ADDR)]", $"[({modelData.Address})]");
pdfContents = pdfContents.Replace("[(A)83(C)83(C)83(N)101(O)]", $"[({modelData.AccountNo})]");
pdfContents = pdfContents.Replace("[(E)95(F)77(F)77(D)82(A)103(T)73(E)]", $"[({modelData.EffectiveDate})]");
pdfContents = pdfContents.Replace("[(E)95(X)71(P)88(D)82(A)83(T)93(E)]", $"[({modelData.ExpireDate})]");
pdfContents = pdfContents.Replace("[(B)71(R)81(A)83(N)81(C)83(H)]", $"[({modelData.Office})]");
pdfContents = pdfContents.Replace("[(I)84(N)81(S)76(U)88(R)101(E)75(D)]", $"[({modelData.Insured})]");
contents.SetData(Encoding.UTF8.GetBytes(pdfContents));
}
the parameter string is formatted due to the stream content resulting like that. the pdf file itself was created by saving a docx document as pdf file.
However an issue happened when certain characters were used:
before replaced
after replaced
as you can see the character G and Q causes the whole text to get jumbled.
It is a frustrating issue since i can’t use another library and writing the whole pdf from scratch is an impossible task too.
The only solution i can think of is that i have to replace the string with the same format but i don’t know how.
Any solution?