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();
  12. canvas.saveState(); // q
  13. canvas.beginText(); // BT
  14. canvas.moveText(, ); // 36 788 Td
  15. canvas.setFontAndSize(BaseFont.createFont(), ); // /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();
  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, ,
  50. , );
  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, ));
  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()) / ,
  78. (PageSize.POSTCARD.getHeight() - img.getScaledHeight()) / );
  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 / );
  88. float cosinus = (float) Math.cos(Math.PI / );
  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, );
  96. over.setTextMatrix(cosinus, sinus, -sinus, cosinus, , );
  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(, , PageSize.POSTCARD.getWidth() - ,
  104. PageSize.POSTCARD.getHeight() - );
  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()) / ,
  14. (PageSize.POSTCARD.getHeight() - img.getScaledHeight()) / );
  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();
  51.  
  52. Document document = new Document();
  53. PdfWriter writer = PdfWriter.getInstance(document,new FileOutputStream(result));
  54. document.open();
  55. // PDPage page = (PDPage)doc.getDocumentCatalog().getAllPages().get( 0 );
  56. Image img = Image.getInstance(resource_jpg);
  57. img.setAbsolutePosition(, );
  58. document.add(img);
  59. document.close();
  60. } catch (FileNotFoundException e)
  61. {
  62. // TODO Auto-generated catch block
  63. e.printStackTrace();
  64. } catch (DocumentException e)
  65. {
  66. // TODO Auto-generated catch block
  67. e.printStackTrace();
  68. } catch (MalformedURLException e)
  69. {
  70. // TODO Auto-generated catch block
  71. e.printStackTrace();
  72. } catch (IOException e)
  73. {
  74. // TODO Auto-generated catch block
  75. e.printStackTrace();
  76. }
  77. }

4、PDF文件转换为图片

  1. package demo1;
  2.  
  3. import java.awt.image.BufferedImage;
  4. import java.io.ByteArrayInputStream;
  5. import java.io.ByteArrayOutputStream;
  6. import java.io.FileOutputStream;
  7. import java.io.OutputStream;
  8.  
  9. import javax.imageio.ImageIO;
  10. import javax.imageio.stream.ImageOutputStream;
  11.  
  12. import org.apache.pdfbox.pdmodel.PDDocument;
  13. import org.apache.pdfbox.pdmodel.PDPage;
  14. import org.apache.pdfbox.util.ImageIOUtil;
  15.  
  16. import com.itextpdf.text.pdf.PdfReader;
  17. import com.itextpdf.text.pdf.PdfStamper;
  18.  
  19. public class PdfPageToImg
  20. {
  21.  
  22. /**
  23. * PDFBOX转图片
  24. *
  25. * @param pdfUrl
  26. * pdf的路径
  27. * @param imgTempUrl
  28. * 图片输出路径
  29. */
  30. public static void pdfToImage(String pdfUrl, String imgTempUrl)
  31. {
  32. try
  33. {
  34. // 读入PDF
  35. PdfReader pdfReader = new PdfReader(pdfUrl);
  36. // 计算PDF页码数
  37. int pageCount = pdfReader.getNumberOfPages();
  38. // 循环每个页码
  39. for (int i = pageCount; i >= pdfReader.getNumberOfPages(); i--)
  40. {
  41. ByteArrayOutputStream out = new ByteArrayOutputStream();
  42. PdfStamper pdfStamper = null;
  43. PDDocument pdDocument = null;
  44.  
  45. pdfReader = new PdfReader(pdfUrl);
  46. pdfReader.selectPages(String.valueOf(i));
  47. pdfStamper = new PdfStamper(pdfReader, out);
  48. pdfStamper.close();
  49. // 利用PdfBox生成图像
  50. pdDocument = PDDocument.load(new ByteArrayInputStream(out
  51. .toByteArray()));
  52. OutputStream outputStream = new FileOutputStream(imgTempUrl
  53. + "ImgName" + "-" + i + ".bmp");
  54.  
  55. ImageOutputStream output = ImageIO
  56. .createImageOutputStream(outputStream);
  57. PDPage page = (PDPage) pdDocument.getDocumentCatalog()
  58. .getAllPages().get();
  59. BufferedImage image = page.convertToImage(
  60. BufferedImage.TYPE_INT_RGB, );
  61. ImageIOUtil.writeImage(image, "bmp", outputStream, );
  62. if (output != null)
  63. {
  64. output.flush();
  65. output.close();
  66. }
  67. pdDocument.close();
  68. }
  69. } catch (Exception e)
  70. {
  71. e.printStackTrace();
  72. }
  73. }
  74.  
  75. public static void main(String[] args)
  76. {
  77. String pdfUrl = "F:\\java56班\\eclipse-SDK-4.2-win32\\iText入门基础教程[2].pdf";
  78. String imgTempUrl = "F:\\java56班\\eclipse-SDK-4.2-win32\\img\\";
  79. pdfToImage(pdfUrl, imgTempUrl);
  80. }
  81. }

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(, , , );
  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 = ; 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

 

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

  1. 【PDF】java使用Itext生成pdf文档--详解

    [API接口]  一.Itext简介 API地址:javadoc/index.html:如 D:/MyJAR/原JAR包/PDF/itext-5.5.3/itextpdf-5.5.3-javadoc/ ...

  2. [.NET开发] C# 合并、拆分PDF文档

    在整理文件时,将多个同类型文档合并是实现文档归类的有效方法,也便于文档管理或者文档传输.当然,也可以对一些比较大的文件进行拆分来获取自己想要的部分文档.可以任意地对文档进行合并.拆分无疑为我们了提供极 ...

  3. 批量将网页转换成图片或PDF文档技巧分享

    工作中我们有时要将一些批量的网页转换成图片或者PDF文档格式,尽管多数浏览器具有滚动截屏或者打印输出PDF文档功能.可是假设有几十上百张网页须要处理,那也是要人命的.所以我一直想找一款可以批量处理该工 ...

  4. C# 复制PDF页面到另一个PDF文档

    C# 复制PDF页面到另一个PDF文档 有时候我们可能有这样一个需求,那就是把PDF页面从一个PDF文档复制到另一个PDF文档中.由于PDF文档并不像word文档那样好编辑,因此复制也相对没有那么容易 ...

  5. Java使用Flying Saucer实现HTML代码生成PDF文档

    1.需要的jar包:org.xhtmlrenderer.flying-saucer-pdf-itext5,Maven依赖如下: <dependency> <groupId>or ...

  6. CentOS6.4下使用默认的文档查看器打开PDF文档乱码的解决方案

     最近在CentOS6.4下使用其默认的文档查看器打开PDF文档时出现乱码的方块,有两种方法可以解决.    方法一:修改/etc/fonts/conf.d/49-sansserif.conf文件,如 ...

  7. 使用Spire PDF for .NET将HTML转换成PDF文档

    目录 开发环境说明 Spire PDF for .NET (free edition)体验 资源下载 开发环境说明 Microsoft Visual Studio 2013 Ultimate Edit ...

  8. C# 打印PDF文档的10种方法

    操作PDF文档时,打印是常见的需求之一.针对不同的打印需求,可分多种情况来进行,如设置静默打印.指定打印页码范围和打印纸张大小.双面打印.黑白打印等等.经过测试,下面将对常见的几种PDF打印需求做一些 ...

  9. 根据传入的文件名称动态从moglifs图片服务器拿到pdf文档并在线浏览

    1.通过百度编辑器上传pdf文档等附件时,在上传方法中将返回的url进行设定,以达到后期点击后可进行浏览的效果: public static final State save(HttpServletR ...

  10. java实现在线浏览PDF文档功能

    实现在线浏览pdf文档功能(本代码适用于项目服务中固定的并且少量的pdf浏览,比如注册时的注册条款在线浏览等): //设置响应内容类型为PDF类型 response.setContentType(&q ...

随机推荐

  1. 关于oracle数据库(3)

    show user ; 查看当前用户的名称 select * from tab;  查看当前用户有哪些表 删除用户 drop user jky cascade; //cascade; 意思是级联操作 ...

  2. npm常用指令

    安装: npm install <name> npm install <name> 安装依赖包,默认安装最新版本,也可在后面加上版本号,并且将安装信息加入项目的package. ...

  3. angular中重要指令介绍($eval,$parse和$compile)

    在angular的服务中,有一些服务你不得不去了解,因为他可以说是ng的核心,而今天,我要介绍的就是ng的两个核心服务,$parse和$compile.其实这两个服务讲的人已经很多了,但是100个读者 ...

  4. Valgrind: memcheck of memleak/mem-uninitialization; massif usage

    first install valgrind, its newest ver is 3.11, and stops updating since 2015/12. in centos, yum ins ...

  5. Ubuntu 12.04 中自定义DNS服务器设置

    首先我们需要创建一个文件/etc/resolvconf/resolv.conf.d/tail: #vim /etc/resolvconf/resolv.conf.d/tail 然后我们在这个文件里写入 ...

  6. sql语句-排序后加入序号再运算判断取想要的项

    select a.id as aid,b.id as bid,a.city,a.cang,a.sid,a.time as atime,b.time as btime,a.price as aprice ...

  7. VMware中Ubuntu 14.04出现Unknown Display问题解决

    如需转载请标明出处:http://blog.csdn.net/itas109 QQ技术交流群:129518033 今天安装完Ubuntu 14.04后,在虚拟机中显示不全,本来调节一下屏幕分辨率就可以 ...

  8. MVC 数据绑定

    在做Asp.Net MVC项目中,都知道View负责页面展示数据或者提供页面收集数据,而所展示的数据或者收集的数据都是从Controller的Action中获取或提交到Controller的Actio ...

  9. Entity FrameWork 实体属性为decimal时默认只保存2位小数

    问题描述:当采用EF的DbContext保存decimal类型数据到数据库,默认只会保存小数点后的前2位小数,其余均置0:例如保存101.182352152322,实际存到数据库里的数据为101.18 ...

  10. C/C++时间函数的使用

    来源:http://blog.csdn.net/apull/article/details/5379819 一.获取日历时间time_t是定义在time.h中的一个类型,表示一个日历时间,也就是从19 ...