【使用Itext处理PDF文档(新建PDF文件、修改PDF文件、PDF中插入图片、将PDF文件转换为图片)】

iText简介

iText是著名的开放源码的站点sourceforge一个项目,是用于生成PDF文档的一个java类库。通过iText不仅可以生成PDF或rtf的文档,而且可以将XML、Html文件转化为PDF文件。 iText的安装非常方便,下载iText.jar文件后,只需要在系统的CLASSPATH中加入iText.jar的路径,在程序中就可以使用iText类库了。
 
1、包的引用
 1 import java.io.FileNotFoundException;
 2 import java.io.FileOutputStream;
 3 import java.io.IOException;
 4 import java.net.MalformedURLException;
 5 import com.itextpdf.text.Document;
 6 import com.itextpdf.text.DocumentException;
 7 import com.itextpdf.text.Element;
 8 import com.itextpdf.text.Font;
 9 import com.itextpdf.text.Font.FontFamily;
10 import com.itextpdf.text.Image;
11 import com.itextpdf.text.PageSize;
12 import com.itextpdf.text.Paragraph;
13 import com.itextpdf.text.Phrase;
14 import com.itextpdf.text.pdf.BaseFont;
15 import com.itextpdf.text.pdf.ColumnText;
16 import com.itextpdf.text.pdf.PdfContentByte;
17 import com.itextpdf.text.pdf.PdfReader;
18 import com.itextpdf.text.pdf.PdfStamper;
19 import com.itextpdf.text.pdf.PdfWriter;

2、创建PDF文件

  1 public void createPDF()
  2     {
  3         try
  4         {
  5             String RESULT = "F:\\java56班\\eclipse-SDK-4.2-win32\\pdfiText.pdf";
  6             Document document = new Document();
  7             PdfWriter writer = PdfWriter.getInstance(document,
  8                     new FileOutputStream(RESULT));
  9             document.open();
 10             PdfContentByte canvas = writer.getDirectContentUnder();
 11             writer.setCompressionLevel(0);
 12             canvas.saveState(); // q
 13             canvas.beginText(); // BT
 14             canvas.moveText(36, 788); // 36 788 Td
 15             canvas.setFontAndSize(BaseFont.createFont(), 12); // /F1 12 Tf
 16             // canvas.showText("Hello World"); // (Hello World)Tj
 17             canvas.showText("你好"); // (Hello World)Tj
 18             canvas.endText(); // ET
 19             canvas.restoreState(); // Q
 20             document.close();
 21         } catch (FileNotFoundException e)
 22         {
 23             // TODO Auto-generated catch block
 24             e.printStackTrace();
 25         } catch (DocumentException e)
 26         {
 27             // TODO Auto-generated catch block
 28             e.printStackTrace();
 29         } catch (IOException e)
 30         {
 31             // TODO Auto-generated catch block
 32             e.printStackTrace();
 33         }
 34     }
 35 
 36     public void createPDF2()
 37     {
 38         try
 39         {
 40             String RESULT = "F:\\java56班\\eclipse-SDK-4.2-win32\\pdfiText.pdf";
 41             Document document = new Document();
 42             PdfWriter writer = PdfWriter.getInstance(document,
 43                     new FileOutputStream(RESULT));
 44             document.open();
 45             writer.setCompressionLevel(0);
 46             // Phrase hello = new Phrase("Hello World");
 47             Phrase hello = new Phrase("你好");
 48             PdfContentByte canvas = writer.getDirectContentUnder();
 49             ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, hello, 200,
 50                     800, 0);
 51             document.close();
 52         } catch (FileNotFoundException e)
 53         {
 54             // TODO Auto-generated catch block
 55             e.printStackTrace();
 56         } catch (DocumentException e)
 57         {
 58             // TODO Auto-generated catch block
 59             e.printStackTrace();
 60         }
 61     }
 62 
 63     public void createPDF3()
 64     {
 65         try
 66         {
 67             String resource_jpg = "F:\\java56班\\eclipse-SDK-4.2-win32\\1.png";//
 68             String RESULT = "F:\\java56班\\eclipse-SDK-4.2-win32\\pdfiText.pdf";
 69             Paragraph p = new Paragraph("Foobar Film Festival", new Font(FontFamily.HELVETICA, 24));
 70             p.setAlignment(Element.ALIGN_CENTER);
 71             Document document = new Document();//
 72             PdfWriter writer = PdfWriter.getInstance(document,new FileOutputStream(RESULT));
 73             document.open();
 74             document.add(p);
 75             Image img = Image.getInstance(resource_jpg);
 76             img.setAbsolutePosition(
 77                     (PageSize.POSTCARD.getWidth() - img.getScaledWidth()) / 2,
 78                     (PageSize.POSTCARD.getHeight() - img.getScaledHeight()) / 2);
 79             
 80 //            img.setAbsolutePosition(0, 0);
 81             document.add(img);
 82             document.newPage();
 83             document.add(p);
 84             document.add(img);
 85             PdfContentByte over = writer.getDirectContent();
 86             over.saveState();
 87             float sinus = (float) Math.sin(Math.PI / 60);
 88             float cosinus = (float) Math.cos(Math.PI / 60);
 89             BaseFont bf = BaseFont.createFont();
 90             over.beginText();
 91             over.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE);
 92             over.setLineWidth(1.5f);
 93             over.setRGBColorStroke(0xFF, 0x00, 0x00);
 94             over.setRGBColorFill(0xFF, 0xFF, 0xFF);
 95             over.setFontAndSize(bf, 36);
 96             over.setTextMatrix(cosinus, sinus, -sinus, cosinus, 50, 324);
 97             over.showText("SOLD OUT");
 98             over.endText();
 99             over.restoreState();
100             PdfContentByte under = writer.getDirectContentUnder();
101             under.saveState();
102             under.setRGBColorFill(0xFF, 0xD7, 0x00);
103             under.rectangle(5, 5, PageSize.POSTCARD.getWidth() - 10,
104                     PageSize.POSTCARD.getHeight() - 10);
105             under.fill();
106             under.restoreState();
107             
108             document.close();
109         } catch (FileNotFoundException e)
110         {
111             // TODO Auto-generated catch block
112             e.printStackTrace();
113         } catch (DocumentException e)
114         {
115             // TODO Auto-generated catch block
116             e.printStackTrace();
117         } catch (MalformedURLException e)
118         {
119             // TODO Auto-generated catch block
120             e.printStackTrace();
121         } catch (IOException e)
122         {
123             // TODO Auto-generated catch block
124             e.printStackTrace();
125         }
126     }

 

3、在绝对位置插入图片

 1 public void addImageAbsolu()
 2     {
 3         try
 4         {
 5             String resource_jpg = "F:\\java56班\\eclipse-SDK-4.2-win32\\1.png";//
 6             String RESULT = "F:\\java56班\\eclipse-SDK-4.2-win32\\pdfiText.pdf";
 7             Document document = new Document();
 8             PdfWriter writer = PdfWriter.getInstance(document,new FileOutputStream(RESULT));
 9             document.open();
10 //            PDPage page = (PDPage)doc.getDocumentCatalog().getAllPages().get( 0 );
11             Image img = Image.getInstance(resource_jpg);
12             img.setAbsolutePosition(
13                     (PageSize.POSTCARD.getWidth() - img.getScaledWidth()) / 2,
14                     (PageSize.POSTCARD.getHeight() - img.getScaledHeight()) / 2);
15             
16 //            img.setAbsolutePosition(0, 0);
17             document.add(img);
18             document.close();
19         } catch (FileNotFoundException e)
20         {
21             // TODO Auto-generated catch block
22             e.printStackTrace();
23         } catch (DocumentException e)
24         {
25             // TODO Auto-generated catch block
26             e.printStackTrace();
27         } catch (MalformedURLException e)
28         {
29             // TODO Auto-generated catch block
30             e.printStackTrace();
31         } catch (IOException e)
32         {
33             // TODO Auto-generated catch block
34             e.printStackTrace();
35         }
36     }
37     
38     public void addImageAbsolu2()
39     {
40         try
41         {
42             String resource_jpg = "F:\\java56班\\eclipse-SDK-4.2-win32\\1.png";//
43             String result = "F:\\java56班\\eclipse-SDK-4.2-win32\\pdfiText.pdf";
44             String result2 = "F:\\java56班\\eclipse-SDK-4.2-win32\\pdfiText2.pdf";
45             //创建一个pdf读入流 
46             PdfReader reader = new PdfReader(result);  
47             //根据一个pdfreader创建一个pdfStamper.用来生成新的pdf. 
48             PdfStamper stamper = new PdfStamper(reader,new FileOutputStream(result2));
49             //获得pdfstamper在当前页的上层打印内容.也就是说 这些内容会覆盖在原先的pdf内容之上. 
50             PdfContentByte over = stamper.getOverContent(0); 
51             
52             
53             Document document = new Document();
54             PdfWriter writer = PdfWriter.getInstance(document,new FileOutputStream(result));
55             document.open();
56 //            PDPage page = (PDPage)doc.getDocumentCatalog().getAllPages().get( 0 );
57             Image img = Image.getInstance(resource_jpg);
58             img.setAbsolutePosition(0, 0);
59             document.add(img);
60             document.close();
61         } catch (FileNotFoundException e)
62         {
63             // TODO Auto-generated catch block
64             e.printStackTrace();
65         } catch (DocumentException e)
66         {
67             // TODO Auto-generated catch block
68             e.printStackTrace();
69         } catch (MalformedURLException e)
70         {
71             // TODO Auto-generated catch block
72             e.printStackTrace();
73         } catch (IOException e)
74         {
75             // TODO Auto-generated catch block
76             e.printStackTrace();
77         }
78     }

4、PDF文件转换为图片

package demo1;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.util.ImageIOUtil;

import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

public class PdfPageToImg
{

    /**
     * PDFBOX转图片
     * 
     * @param pdfUrl
     *            pdf的路径
     * @param imgTempUrl
     *            图片输出路径
     */
    public static void pdfToImage(String pdfUrl, String imgTempUrl)
    {
        try
        {
            // 读入PDF
            PdfReader pdfReader = new PdfReader(pdfUrl);
            // 计算PDF页码数
            int pageCount = pdfReader.getNumberOfPages();
            // 循环每个页码
            for (int i = pageCount; i >= pdfReader.getNumberOfPages(); i--)
            {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                PdfStamper pdfStamper = null;
                PDDocument pdDocument = null;

                pdfReader = new PdfReader(pdfUrl);
                pdfReader.selectPages(String.valueOf(i));
                pdfStamper = new PdfStamper(pdfReader, out);
                pdfStamper.close();
                // 利用PdfBox生成图像
                pdDocument = PDDocument.load(new ByteArrayInputStream(out
                        .toByteArray()));
                OutputStream outputStream = new FileOutputStream(imgTempUrl
                        + "ImgName" + "-" + i + ".bmp");

                ImageOutputStream output = ImageIO
                        .createImageOutputStream(outputStream);
                PDPage page = (PDPage) pdDocument.getDocumentCatalog()
                        .getAllPages().get(0);
                BufferedImage image = page.convertToImage(
                        BufferedImage.TYPE_INT_RGB, 96);
                ImageIOUtil.writeImage(image, "bmp", outputStream, 96);
                if (output != null)
                {
                    output.flush();
                    output.close();
                }
                pdDocument.close();
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public static void main(String[] args)
    {
        String pdfUrl = "F:\\java56班\\eclipse-SDK-4.2-win32\\iText入门基础教程[2].pdf";
        String imgTempUrl = "F:\\java56班\\eclipse-SDK-4.2-win32\\img\\";
        pdfToImage(pdfUrl, imgTempUrl);
    }
}

5、图片集转换为PDF文件

 1 package demo1;
 2 
 3 import java.io.File;
 4 import java.io.FileOutputStream;
 5 import java.io.IOException;
 6 import com.itextpdf.text.Document;
 7 import com.itextpdf.text.DocumentException;
 8 import com.itextpdf.text.Image;
 9 import com.itextpdf.text.Rectangle;
10 import com.itextpdf.text.pdf.PdfWriter;
11 
12 public class ImgToPDF
13 {
14 
15     /**
16      * 
17      * @param destPath
18      *            生成pdf文件的路劲
19      * @param images
20      *            需要转换的图片路径的数组
21      * @throws IOException
22      * @throws DocumentException
23      */
24     public static void imagesToPdf(String destPath, String imagesPath)
25     {
26         try
27         {
28             // 第一步:创建一个document对象。
29             Document document = new Document();
30             document.setMargins(0, 0, 0, 0);
31             // 第二步:
32             // 创建一个PdfWriter实例,
33             PdfWriter.getInstance(document, new FileOutputStream(destPath));
34             // 第三步:打开文档。
35             document.open();
36             // 第四步:在文档中增加图片。
37             File files = new File(imagesPath);
38             String[] images = files.list();
39             int len = images.length;
40 
41             for (int i = 0; i < len; i++)
42             {
43                 if (images[i].toLowerCase().endsWith(".bmp"))
44                 {
45                     String temp = imagesPath + "\\" + images[i];
46                     Image img = Image.getInstance(temp);
47                     img.setAlignment(Image.ALIGN_CENTER);
48                     // 根据图片大小设置页面,一定要先设置页面,再newPage(),否则无效
49                     document.setPageSize(new Rectangle(img.getWidth(), img
50                             .getHeight()));
51                     document.newPage();
52                     document.add(img);
53                 }
54             }
55             // 第五步:关闭文档。
56             document.close();
57         } catch (Exception e)
58         {
59             // TODO Auto-generated catch block
60             e.printStackTrace();
61         }
62     }
63 
64     public static void main(String[] args)
65     {
66         String destPath = "F:\\java56班\\eclipse-SDK-4.2-win32\\img\\imagesToPdf.pdf";
67         String imagesPath = "F:\\java56班\\eclipse-SDK-4.2-win32\\img\\";
68         imagesToPdf(destPath, imagesPath);
69     }
70 
71 }

 

2015-01-26

 
posted @ 2015-01-26 22:41  tankqiu  阅读(16530)  评论(5编辑  收藏  举报