问题
This Code is perfect. But the only problem is that I want to copy links and I want to change the property of links to inherit zoom.
public class links {
public static void main(String[] args) throws DocumentException, IOException,FileNotFoundException {
String src = "E:/bookmark.pdf";
String destination = "E:/links.pdf";
PdfReader reader=new PdfReader(src);
reader.consolidateNamedDestinations();
Document doc=new Document();
PdfCopy pdfCopy = new PdfCopy(doc,new FileOutputStream(destination));
doc.open();
int n = reader.getNumberOfPages();
PdfDestination d = new PdfDestination(PdfDestination.XYZ,-1,-1,0.0F) ;
PdfAction act = PdfAction.gotoLocalPage(1, d, pdfCopy);
for (int i=1; i <= n ;i++)
{
PdfDictionary pageDic = reader.getPageN(i);
PdfArray arrayann = pageDic.getAsArray(PdfName.ANNOTS);
if (arrayann != null)
{
//reader.addPdfObject(pageDic.get(PdfName.ANNOTS));
PdfArray annot=(PdfArray)PdfReader.getPdfObject(pageDic.get(PdfName.ANNOTS));
ArrayList<PdfObject> arrAnnot = new ArrayList<PdfObject>();
arrAnnot = annot.getArrayList();
for (int j = 0; j < arrAnnot.size(); j++)
{
PdfDictionary annots = (PdfDictionary)PdfReader.getPdfObject(arrAnnot.get(j));
if (PdfName.LINK.equals(annots.get(PdfName.SUBTYPE)))
{
annots.remove(PdfName.DEST);
annots.put(PdfName.DEST,act);
}
}
}
pdfCopy.addPage(pdfCopy.getImportedPage(reader, i));
pdfCopy.freeReader(reader);
}
reader.close();
pdfCopy.close();
doc.close();
System.out.println("The Pdf is Created..");
}
}
回答1:
Please take a look at the ChangeZoomXYZDestination example. You'll soon discover that your allegation "This Code is perfect" is wrong. As I already indicated in my comments, you shouldn't use PdfCopy
, you should use PdfStamper
. Also, you shouldn't replace the destination, you should replace the zoom factor.
Take for instance the file xyz_destination.pdf on page 11, there are 10 links to the 10 previous pages, each with an /XYZ
destination pointing at a specific page with a specific zoom factor. You can see this in the following screen shot:
In the first annotation, the zoom factor is 1, in the second it's 2, and so on.
If you want to change the zoom factor of these links to 0, then you need to loop over the annotations (you already do this), but instead of replacing the /DEST
incorrectly with an action, you need to change the value of the zoom-factor in the /DEST
array:
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));
}
}
Now you will have a file such as xyz_zoom.pdf where the zoom factor of all links of type /XYZ
will be zero.
来源:https://stackoverflow.com/questions/22828782/all-links-of-existing-pdf-change-the-action-property-to-inherit-zoom-itext-lib