[研究]ASP.NET WebForm 使用 Spire.Pdf ( FreeSpire.PDF 8.6.0) 套件,文字增加底色
2025-10-13
環境:Visual Studio 2022 + ASP.NET + WebForm + Web Application + C# + SQL Server 2019 + SQL Server Management Studio (SSMS) 19
********************************************************************************
foreach (PdfTextFind find in page.FindText("DD – MM - 2025", TextFindParameter.IgnoreCase).Finds)
{
rec = find.TextBounds[0];
page.Canvas.DrawRectangle(PdfBrushes.Black, rec);
rec.Width = PdfPageSize.A4.Width - rec.X * 2;
rec.Height = rec.Y + 20;
string date = DateTime.Now.ToString("dd-MM-yyyy");
page.Canvas.DrawString(date, new PdfTrueTypeFont(new Font("微軟正黑體", 14, FontStyle.Regular), true), brush, rec);
}
|
ChatGPT
foreach (PdfTextFind find in page.FindText("DD – MM - 2025", TextFindParameter.IgnoreCase).Finds)
{
rec = find.TextBounds[0];
// 建立指定色碼 (#38B394) 的刷子
PdfBrush customBrush = new PdfSolidBrush(new PdfRGBColor(0x38, 0xB3, 0x94));
// 畫底色
page.Canvas.DrawRectangle(customBrush, rec);
// 調整繪製區域寬高
rec.Width = PdfPageSize.A4.Width - rec.X * 2;
rec.Height = rec.Y + 20;
// 寫入新的日期文字
string date = DateTime.Now.ToString("dd-MM-yyyy");
page.Canvas.DrawString(
date,
new PdfTrueTypeFont(new Font("微軟正黑體", 14, FontStyle.Regular), true),
PdfBrushes.White, // 若底色深,字用白色會更清楚
rec
);
}
|
********************************************************************************
2025-10-14 補充
一、這個方法預設沒有底色。也就是說,除非你額外在文字後面繪製了矩形或指定背景筆刷,否則文字是「透明背景」直接疊在 PDF 的頁面上。
page.Canvas.DrawString(...) |
二、目前的程式碼會造成「有底色」的原因
page.Canvas.DrawRectangle(PdfBrushes.Black, rec); |
這一行其實會先在該區域畫一個「黑色實心矩形」。
所以當你後面再 DrawString() 畫文字時,視覺上就像文字有「黑底」。
這並不是 DrawString 預設有底色,而是你手動畫出來的。
三、讓底色變透明的方式
foreach (PdfTextFind find in page.FindText("DD – MM - 2025", TextFindParameter.IgnoreCase).Finds)
{
RectangleF rec = find.TextBounds[0];
string date = DateTime.Now.ToString("dd-MM-yyyy");
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("微軟正黑體", 14, FontStyle.Regular), true);
PdfSolidBrush brush = new PdfSolidBrush(Color.Black); // 文字顏色
page.Canvas.DrawString(date, font, brush, rec);
}
|
實際測試,底色透明後,原來想替換的字會顯示出來,造成文字重疊。
Spire.PDF 的 FindText() 雖能找到文字區域,但不會刪除原文字物件。
page.Canvas.DrawString() 只是繪製新內容,無法覆蓋或刪除原字元。
要達成「替換文字」的視覺效果,你通常需要遮蓋原文字再寫新字。
PdfPage.ReplaceText(oldText, newText) 只有 Spire.PDF Pro 付費版 才支援;
免費版或標準版只能用上面「畫矩形 + 重畫文字」的方式模擬替換。
(完)
相關
[研究]FreeSpire.PDF 10.2.0和中文相容有問題,Spire.PDF 10.10.5 或 FreeSpire.PDF 8.6.0正常
https://shaurong.blogspot.com/2024/10/freespirepdf-1020spirepdf-10105.html
沒有留言:
張貼留言