PDF layers allow users to selectively hide or show the content appearing on them in PDF documents. In this article, we will introduce how to add layers to a PDF document, draw content to the layers and delete a specific layer in Java usingFree Spire.PDF for Java library.
Before getting started, please download Free Spire.PDF for Java package throughthis link, unzip the package and then import Spire.Pdf.jar from lib folder into our application.
Add layers to a PDF
In the below example, we will learn how to add two layers to a PDF document and draw the content of a PDF page and an image to the layers.
importcom.spire.pdf.PdfDocument;importcom.spire.pdf.PdfPageBase;importcom.spire.pdf.graphics.*;importcom.spire.pdf.PdfPageSize;importcom.spire.pdf.graphics.layer.PdfLayer;importjava.awt.*;importjava.awt.geom.Point2D;publicclassAddLayers{publicstaticvoidmain(String[]args)throwsException{//Create a new PDF documentPdfDocumenttarget=newPdfDocument();//Add a pagePdfPageBasepage=target.getPages().add();//Load an existing PDF documentPdfDocumentpdf=newPdfDocument();pdf.loadFromFile("Instruction.pdf");//Create a template of the first page in the PDFPdfTemplatetemplate=pdf.getPages().get(0).createTemplate();//Add a layer to the new created PDFPdfLayerlayer1=target.getLayers().addLayer("Layer 1");PdfCanvascanvas1=layer1.createGraphics(page.getCanvas());//Draw the template to the layercanvas1.drawTemplate(template,newPoint2D.Float(20,50),PdfPageSize.A4);//Add a layer to the new created PDFPdfLayerlayer2=target.getLayers().addLayer("Layer 2");PdfCanvascanvas2=layer2.createGraphics(page.getCanvas());//Draw an image to the layercanvas2.drawImage(PdfImage.fromFile("Hydrangeas.jpg"),newPoint2D.Float(330,125),newDimension(200,130));//Save the resultant documenttarget.saveToFile("result.pdf");}}
Delete a specific layer
The below example shows how to remove a specific layer along with its content from a PDF document.
importcom.spire.pdf.PdfDocument;publicclassDeleteLayer{publicstaticvoidmain(String[]args){//Load the PDFPdfDocumentpdf=newPdfDocument();pdf.loadFromFile("result.pdf");//Remove the layer named "Layer 1" and its content from the PDFpdf.getLayers().removeLayer("Layer 1",true);//Save the resultant documentpdf.saveToFile("deleteLayer.pdf");pdf.close();}}
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse