pdf删除图层
PDF层允许用户有选择地隐藏或显示PDF文档中出现在其上的内容。 在本文中,我们将介绍如何使用Free Spire.PDF for Java库在Java文档中添加图层,在图层中绘制内容以及在Java中删除特定图层。
在开始之前,请通过此链接下载Java的Free Spire.PDF软件包,解压缩该软件包,然后从lib文件夹将Spire.Pdf.jar导入到我们的应用程序中。
将层添加到PDF
在下面的示例中,我们将学习如何在PDF文档中添加两层,以及如何将PDF页面的内容和图像绘制到这些层。
import com.spire.pdf.PdfDocument ;
import com.spire.pdf.PdfPageBase ;
import com.spire.pdf.graphics.* ;
import com.spire.pdf.PdfPageSize ;
import com.spire.pdf.graphics.layer.PdfLayer ;
import java.awt.* ;
import java.awt.geom.Point2D ;
public class AddLayers {
public static void main ( String [] args ) throws Exception {
//Create a new PDF document
PdfDocument target = new PdfDocument ();
//Add a page
PdfPageBase page = target . getPages (). add ();
//Load an existing PDF document
PdfDocument pdf = new PdfDocument ();
pdf . loadFromFile ( "Instruction.pdf" );
//Create a template of the first page in the PDF
PdfTemplate template = pdf . getPages (). get ( 0 ). createTemplate ();
//Add a layer to the new created PDF
PdfLayer layer1 = target . getLayers (). addLayer ( "Layer 1" );
PdfCanvas canvas1 = layer1 . createGraphics ( page . getCanvas ());
//Draw the template to the layer
canvas1 . drawTemplate ( template , new Point2D . Float ( 20 , 50 ), PdfPageSize . A4 );
//Add a layer to the new created PDF
PdfLayer layer2 = target . getLayers (). addLayer ( "Layer 2" );
PdfCanvas canvas2 = layer2 . createGraphics ( page . getCanvas ());
//Draw an image to the layer
canvas2 . drawImage ( PdfImage . fromFile ( "Hydrangeas.jpg" ), new Point2D . Float ( 330 , 125 ), new Dimension ( 200 , 130 ));
//Save the resultant document
target . saveToFile ( "result.pdf" );
}
}
删除特定图层
以下示例显示了如何从PDF文档中删除特定图层及其内容。
import com.spire.pdf.PdfDocument ;
public class DeleteLayer {
public static void main ( String [] args ){
//Load the PDF
PdfDocument pdf = new PdfDocument ();
pdf . loadFromFile ( "result.pdf" );
//Remove the layer named "Layer 1" and its content from the PDF
pdf . getLayers (). removeLayer ( "Layer 1" , true );
//Save the resultant document
pdf . saveToFile ( "deleteLayer.pdf" );
pdf . close ();
}
}
翻译自: https://dev.to/eiceblue/add-and-delete-layers-in-pdf-in-java-53an
pdf删除图层