Outputstream - 创建不可编辑的pdf文件

时间:2013-08-21 06:50:59

标签: java pdf outputstream fileoutputstream readonly

下面的代码用于编写pdf文件;

BaseFont bf = BaseFont.createFont(FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
FontSelector fs = new FontSelector();
fs.addFont(new Font(bf));                
String fileName = filePath3 + "//DEVIATION_REPORT.pdf";
OutputStream file = new FileOutputStream(new File(fileName));
Font smallFont = new Font(Font.FontFamily.COURIER, 6, Font.NORMAL);
Font headerFont = new Font(Font.FontFamily.HELVETICA, 7, Font.BOLD);
Font tabFont = new Font(Font.FontFamily.HELVETICA, 5, Font.NORMAL);
Font rusFont = new Font(bf, 5);                
Font blueFont = new Font(bf, 5);
blueFont.setColor(BaseColor.BLUE);                
Font redFont = new Font(bf, 5);
redFont.setColor(BaseColor.RED);

String comType;
if (compType == 2)
   comType = "Character";
else 
   comType = "Word";

Document doc = new Document();
PdfWriter.getInstance(doc, file);                
doc.open();            

Image image1 = Image.getInstance(cmdpath + "ScRp.jpg");
image1.setAlignment(Element.ALIGN_LEFT);

Paragraph prg = new Paragraph("Compare", smallFont);
prg.setAlignment(Element.ALIGN_RIGHT);
doc.add(image1);
doc.add(prg);
doc.add(new Paragraph("__________________________________________________"));
doc.add(new Paragraph("Passed Report"));
doc.add(new Paragraph(" "));

PdfPTable table = new PdfPTable(2);
PdfPCell cell1 = new PdfPCell(new Paragraph("No", headerFont));
cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
cell1.setPaddingBottom(5);                
PdfPCell cell2 = new PdfPCell(new Paragraph("Details", headerFont));
cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
cell2.setPaddingBottom(5);             
table.addCell(cell1);
table.addCell(cell2);
doc.add(table);
doc.newPage();
doc.close();
file.close();

如果我想让pdf不可编辑,该怎么办?我试过用

 PdfEncryptor.encrypt(  
 new PdfReader(fileName),  
 new FileOutputStream("HelloWorldProtected.pdf"),  
 null,  
 "StrongPassword".getBytes(),  
 PdfWriter.AllowPrinting,  
 PdfWriter.STRENGTH128BITS);  

但编译器在这里停止。我等了15分多钟但没有任何事情发生。

我甚至制作了 file.setreadOnly(),但是编辑后用户无法保存。它仍然允许用户编辑。用户可以另存为文档,并替换为不可编辑的文档。

还有其他方法可以让文件不可编辑。请指教。

1 个答案:

答案 0 :(得分:0)

如果您的项目很好,您可能希望使用iText进行此类工作。我现在无法看到任何其他选项。我亲自使用iText,它非常强大。如果这有帮助,请告诉我。

编辑:

  1. Encryption settings
  2. http://viralpatel.net/blogs/password-protect-pdf-itext-java/
  3. http://www.jarfinder.com/index.php/java/info/com.lowagie.text.pdf.interfaces.PdfEncryptionSettings
  4. 尝试在Google和SO上搜索更多内容
  5. 编辑:等待15分钟。问题可能是文件路径上的文件写入权限。

相关问题