![](/img/trans.png)
[英]How do I modify external link in an existing PDF such that it points to an internal page within document using IText7 and C#?
[英]How do I underline internal links in an existing PDF using IText7 and C#?
我們經常使用Word生成帶有許多內部交叉引用的大型文檔。 我正在寫一個工具來查找可點擊的內部交叉引用並在其中添加藍色下划線。 (我知道我可以在Word級別上執行此操作,但是即使我無權訪問原始Word文件,也需要能夠執行此操作。)
我正在使用C#和IText7。我能夠加載和掃描現有PDF的這些內部鏈接。 但是我似乎無法做的是更改鏈接的外觀。 搜索之后,我了解到PdfAnnotation
類用於創建新鏈接,而不是用於更改現有鏈接。 有人告訴我我需要使用Put()
來更改現有的。 我嘗試了許多不同的方法,但是似乎都沒有用。
var pdfDoc = new PdfDocument(new PdfReader(txt_FileLoaded.Text), new PdfWriter(outfile));
for (int x = pgStart; x <= pgEnd; x++)
{
PdfPage page = pdfDoc.GetPage(x);
var annotations = page.GetAnnotations();
foreach (var a in annotations)
{
if (a.GetSubtype() == PdfName.Link)
{
PdfLinkAnnotation link = (PdfLinkAnnotation)a;
var action = link.GetAction();
if (action != null)
{
if (
(action.Get(PdfName.S) == PdfName.URI) ||
(action.Get(PdfName.S) == PdfName.GoToR) )
{
//Do something with external links if you want
}
else if (
(action.Get(PdfName.S) == PdfName.GoTo) ||
(action.Get(PdfName.S) == PdfName.GoToE))
{
//Do something with internal links
link.Put(PdfName.C, new PdfArray(ColorConstants.BLUE.GetColorValue()));
link.Put(PdfName.Border, new PdfArray(new int[] {0,0,5}));
}
}
}
}
}
pdfDoc.Close();
當我調用Close()
,新文件已正確寫入,但沒有出現下划線。 再次,我確認確實可以找到鏈接。 我需要通過Put()
進行哪些具體更改才能添加這些下划線?
謝謝你的時間!!
據我所知,您試圖實現的目標無法僅通過修改注釋對象來實現。 也許可以嘗試使用外觀流,但是我不確定它是否會起作用,即使會帶來一些副作用。
批注僅對可單擊的矩形區域和單擊該區域時將觸發的動作(或目標)進行編碼。 也可以配置注釋的邊框,但是PDF規范不允許您進行細調,因此您將無法僅設置底部邊框來模擬下划線。
相反,我們要做的是直接在頁面的內容中畫一條線,希望注釋位置足夠准確。
我們可以使用annotation.getRectangle()
PdfCanvas
annotation.getRectangle()
獲得注解的區域,然后使用PdfCanvas
繪制一條具有匹配坐標的線(如果需要,您也可以將其向上移動一點)。 該代碼使用Java,但是您會發現轉換為C#非常容易,因為只有方法名稱以大寫字母開頭。
PdfPage page = pdfDocument.getPage(i);
// Create canvas where we would draw additional lines
PdfCanvas pageCanvas = new PdfCanvas(page);
for (PdfAnnotation annotation : page.getAnnotations()) {
Rectangle annotationArea = annotation.getRectangle().toRectangle();
// Draw a line at the bottom of the annotation area
pageCanvas.setStrokeColor(ColorConstants.BLUE).
moveTo(annotationArea.getLeft(), annotationArea.getBottom()).
lineTo(annotationArea.getRight(), annotationArea.getBottom()).
stroke();
}
初始PDF如下所示:
這是輸出PDF的樣子
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.