java生成pdf文件
2011年12月31日11:02 阅读: 22969 次
标签: PDF, Java
01 |
package com.hundsun.gildata.irp.core.action; |
04 |
import java.io.FileOutputStream; |
05 |
import java.io.IOException; |
06 |
import com.hundsun.gildata.irp.common.util.ItextUtils; |
07 |
import com.itextpdf.text.Document; |
08 |
import com.itextpdf.text.PageSize; |
09 |
import com.itextpdf.text.pdf.PdfWriter; |
11 |
public class MakePdfTest { |
13 |
???? private String att; |
15 |
???? public void makdPdf() throws IOException { |
18 |
???????? final int margin = 10 ; |
19 |
???????? String filePath = "d:/aaa/" ; |
20 |
???????? String fileName = "aa.pdf" ; |
22 |
???????? att = filePath + fileName; |
24 |
???????? File file = new File(filePath); |
25 |
???????? if (!file.exists()) { |
26 |
???????????? file.mkdirs(); |
28 |
???????? Document document = null ; |
29 |
???????? FileOutputStream fos = null ; |
30 |
???????? PdfWriter pdf = null ; |
32 |
???????????? document = new Document(PageSize.A4, margin, margin, margin, margin); |
33 |
???????????? fos = new FileOutputStream(filePath + fileName); |
34 |
???????????? pdf = PdfWriter.getInstance(document, fos); |
35 |
???????????? document.open(); |
37 |
???????????? String summary = "? this is a pdf made bycode\n? 另起一行" .replaceAll( "\n" , " " ).replaceAll( " " , " " ); |
38 |
???????????? document.add(ItextUtils.processViewpoint(summary)); |
40 |
???????????? att = filePath + fileName; |
43 |
???????? } catch (Exception e) { |
46 |
???????????? if (document != null ) { |
47 |
???????????????? document.close(); |
49 |
???????????? if (pdf != null ) { |
50 |
???????????????? pdf.close(); |
52 |
???????????? if (fos != null ) { |
53 |
???????????????? fos.close(); |
59 |
???? public static void main(String[] args) { |
61 |
???????? MakePdfTest testMake = new MakePdfTest(); |
63 |
???????????? testMake.makdPdf(); |
64 |
???????????? System.out.println(testMake.att); |
65 |
???????? } catch (IOException e) { |
66 |
???????????? e.printStackTrace(); |