[Fact]
public void Test_ReplaceChinese()
{
byte[] bytes = null;
using (var fileStream = File.OpenRead("D:\\ba99显示不全.pdf"))
{
bytes = new byte[fileStream.Length];
fileStream.Read(bytes, 0, bytes.Length);
fileStream.Close();
}
using var stream = new MemoryStream(bytes);
var pdfDoc = new Aspose.Pdf.Document(stream);
Replace(pdfDoc, "$$SignName$$", "王老五");
Replace(pdfDoc, "$$SignTime$$", "2021-10-08");
pdfDoc.Save("D:\\123_output.pdf");
}
private void Replace(Aspose.Pdf.Document mDoc,string oldText,string newText)
{
TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber(oldText);
// Accept the absorber for all the pages
mDoc.Pages.Accept(textFragmentAbsorber);
// Get the extracted text fragments
TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments;
// Loop through the fragments
foreach (TextFragment textFragment in textFragmentCollection)
{
// Update text and other properties
textFragment.Text = newText;
//textFragment.TextState.Font = FontRepository.FindFont("Verdana"); // 中文无法展示
textFragment.TextState.Font = GetSimHeiFont();
textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Black);
}
}