package com.me.test; import java.awt.*; import java.io.*; import com.lowagie.text.*; import com.lowagie.text.Font; import com.lowagie.text.Image; import com.lowagie.text.Rectangle; import com.lowagie.text.pdf.BaseFont; import com.lowagie.text.pdf.PdfContentByte; import com.lowagie.text.pdf.PdfReader; import com.lowagie.text.pdf.PdfWriter; /** * 通过给定的短语生成pdf文件,并且加密 */ /** * First iText example: Hello World. */ public class HelloWorld { /** Path to the resulting PDF file. */ public static final String RESULT = "f:/hello.pdf"; public static final String pwd = "123456"; public static final String result = "f:/Itext/b.gif"; /** * Creates a PDF file: hello.pdf * * @param args * no arguments needed */ public static void main(String[] args) throws DocumentException, IOException { new HelloWorld().createPdf(RESULT); } /** * Creates a PDF document. * * @param filename * the path to the new PDF document * @throws DocumentException * @throws IOException */ public void createPdf(String filename) throws DocumentException, IOException { // 设定文本样式 Rectangle rec = new Rectangle(PageSize.A4); rec.setBackgroundColor(Color.GRAY); rec.setBorder(Rectangle.TOP); rec.setBorderColor(Color.black); rec.setBorderWidth(50); // 创建本文 Document doc = new Document(rec, 100, 201, 20, 20); // 设定路径 PdfWriter pdf = PdfWriter.getInstance(doc, new FileOutputStream( HelloWorld.RESULT)); // 设定布局 pdf.setViewerPreferences(PdfWriter.PageModeUseThumbs | PdfWriter.PageLayoutTwoColumnLeft | PdfWriter.HideMenubar); // 加密 pdf.setEncryption(pwd.getBytes(), pwd.getBytes(), PdfWriter.ALLOW_COPY | PdfWriter.ALLOW_PRINTING, PdfWriter.STANDARD_ENCRYPTION_40); // 设置中文 BaseFont base = null; Font fontChinese = null; try { base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED); fontChinese = new Font(base, 18, Font.BOLD); } catch (DocumentException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } doc.open(); doc.add(new Paragraph("我是Pro", fontChinese)); doc.close(); } }
