图层使我们可以在pdf文档中选择性地隐藏或显示部分内容。spire.pdf for java支持添加线条、图片、文字、矩形等多种样式的图层到pdf文档,也支持从pdf文档中删除图层。本文将介绍如何使用spire.pdf for java添加和删除pdf图层。
添加图层
import com.spire.pdf.pdfdocument;
import com.spire.pdf.pdfpagebase;
import com.spire.pdf.graphics.pdfbrushes;
import com.spire.pdf.graphics.pdfcanvas;
import com.spire.pdf.graphics.pdfpen;
import com.spire.pdf.graphics.layer.pdflayer;
import java.awt.geom.point2d;
public class addlayers {
public static void main(string[] args){
//创建pdf文档
pdfdocument pdf = new pdfdocument();
//添加一页
pdfpagebase page = pdf.getpages().add();
//添加3个线条图层到pdf文档
pdflayer layer = pdf.getlayers().addlayer("red line1");
pdfcanvas canvas1 = layer.creategraphics(pdf.getpages().get(0).getcanvas());
canvas1.drawline(new pdfpen(pdfbrushes.getred(), 1), new point2d.float(50, 350), new point2d.float(200, 350));
layer = pdf.getlayers().addlayer("blue line1");
pdfcanvas canvas2 = layer.creategraphics(pdf.getpages().get(0).getcanvas());
canvas2.drawline(new pdfpen(pdfbrushes.getblue(), 1), new point2d.float(50, 450), new point2d.float(200, 450));
layer = pdf.getlayers().addlayer("green line1");
pdfcanvas canvas3 = layer.creategraphics(pdf.getpages().get(0).getcanvas());
canvas3.drawline(new pdfpen(pdfbrushes.getgreen(), 1), new point2d.float(50,550), new point2d.float(200, 550));
//保存结果文档
pdf.savetofile("output/addlayers.pdf");
pdf.close();
}
}
删除图层
import com.spire.pdf.pdfdocument;
public class deletelayers {
public static void main(string[] args){
//加载pdf文档
pdfdocument pdf = new pdfdocument();
pdf.loadfromfile("output/addlayers.pdf");
//删除名为“red line1”的图层
pdf.getlayers().removelayer("red line1");
//保存结果文档
pdf.savetofile("output/deletelayer.pdf");
pdf.close();
}
}