之前找了好久没有找到好的办法,今天无意间看到的博客,解决了我的问题,这下也不用借助第三方pdf阅读器了,使用adobe reader 就可以在线打开pdf了,项目在一定程度上节省了费用。
import java.io.FileOutputStream;
import java.io.IOException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfEncryptor;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;
public class PdfHandle {
public void hideBars(String inputFile, String outFile) {
//复制一个PDF
// 创建一个reader
try {
PdfReader reader =new PdfReader(inputFile);
int n = reader.getNumberOfPages();
// 得到第一页
Rectangle psize = reader.getPageSize(1);
float width = psize.getHeight();
float height = psize.getWidth();
// step 1: 创建一个document对象
Document document =new Document(new Rectangle(width, height));
// step 2: 创建一个write
PdfCopy writer =new PdfCopy(document,new FileOutputStream(outFile));
//设置隐藏菜单栏和工具栏
writer.setViewerPreferences(PdfWriter.HideMenubar | PdfWriter.HideToolbar);
// step 3: 打开 document
document.open();
// step 4:一页一页添加内容
int i = 0;
while (i < n) {
document.newPage();
i++;
PdfImportedPage page1 = writer.getImportedPage(reader, i);
writer.addPage(page1);
}
// step 5: 关闭document
document.close();
} catch (IOException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
}
public void notAllowPrint(String inputFile,String outFile)
{
try {
PdfReader reader =new PdfReader(inputFile);
//设置加密权限
PdfEncryptor.encrypt(reader,
new FileOutputStream(outFile),
null,
null,
PdfWriter.AllowAssembly |PdfWriter.AllowFillIn|PdfWriter.AllowScreenReaders,
false);
}
catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String args[])
{
PdfHandle pp=new PdfHandle();
pp.hideBars("e://3.pdf","e://4.pdf");
pp.notAllowPrint("e://4.pdf","e://5.pdf");
}
}
经过测试确实是OK,项目中需要的jar包有:itextpdf-5.3.2.jar 、bcprov-jdk15on-1.47.jar、bcpkix-jdk15on-1.47.jar、bcmail-jdk15on-1.47.jar
参考https://blog.csdn.net/tanguang_honesty/article/details/8530696