使用iText
在Java
中更改縮放級別的代碼在iText home page中給出。我想將它轉換爲C#
。無數小時後,我終於重寫了代碼,只是發現它沒有改變任何鏈接。這意味着我一定犯了錯誤。以PDF格式更改所有鏈接目標中的縮放級別
編輯:
按照要求,請看看在simple PDF example。
我的代碼如下:
using (var reader = new PdfReader(input))
{
using (var stamper = new PdfStamper(reader, ms))
{
for (int i = 1; i <= reader.NumberOfPages; i++)
{
// Get a page of a PDF page
PdfDictionary page = reader.GetPageN(i);
// Get all the annotations of page i
PdfArray annotsArray = page.GetAsArray(PdfName.ANNOTS);
// If page does not have annotations
if (annotsArray == null)
{
continue;
}
// For each annotation
for (int j = 0; j < annotsArray.Size; j++)
{
// for current annotation
PdfDictionary annotation = annotsArray.GetAsDict(j);
// test if it is LINK
PdfDictionary annotationAction = annotation.GetAsDict(PdfName.A);
if (annotationAction == null || PdfName.LINK.Equals(annotationAction.Get(PdfName.S)))
{
PdfArray d = annotation.GetAsArray(PdfName.DEST);
if (d != null && d.Length == 5 && PdfName.XYZ.Equals(d.GetAsName(1)))
{
d[4] = new PdfNumber(150);
}
}
}
}
}
}
在Java中
原始代碼要短得多:
public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
PdfReader reader = new PdfReader(src);
PdfDictionary page = reader.getPageN(11);
PdfArray annots = page.getAsArray(PdfName.ANNOTS);
for (int i = 0; i < annots.size(); i++) {
PdfDictionary annotation = annots.getAsDict(i);
if (PdfName.LINK.equals(annotation.getAsName(PdfName.SUBTYPE))) {
PdfArray d = annotation.getAsArray(PdfName.DEST);
if (d != null && d.size() == 5 && PdfName.XYZ.equals(d.getAsName(1)))
d.set(4, new PdfNumber(0));
}
}
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
stamper.close();
}
修訂EDIT 2
感謝@mkl我已經想出了與解決方案。
for (int i = 1; i <= reader.NumberOfPages; i++)
{
PdfDictionary page = reader.GetPageN(i);
PdfArray annotsArray = page.GetAsArray(PdfName.ANNOTS);
if (annotsArray == null)
{
continue;
}
for (int j = 0; j < annotsArray.Size; j++)
{
PdfDictionary annotation = annotsArray.GetAsDict(j);
PdfDictionary annotationAction = annotation.GetAsDict(PdfName.A);
if (PdfName.GOTO.Equals(annotationAction.Get(PdfName.S)))
{
PdfArray d = annotationAction.GetAsArray(PdfName.D);
if (d != null)
{
Console.WriteLine(d[4]);
d[4] = new PdfNumber(1.20);
}
}
}
}
您的代碼僅處理** XYZ **類型的目標。可能你的例子pdf使用其他類型的目的地。因此,請分享您的測試pdf。 – mkl
@mkl我剛剛添加了一個示例文件。 – menteith
*'PdfArray d = annotation.GetAsArray(PdfName.GOTO)'* - 這在兩種方式上是錯誤的:您想要名爲** D **的數組,而不是名爲** GoTo **的數組,並且此數組包含在'annotationAction'中,不直接在'annotation'中。因此:'PdfArray d = annotationAction.GetAsArray(PdfName.D)' – mkl