【使用Itext处理PDF文档(新建PDF文件、修改PDF文件、PDF中插入图片、将PDF文件转换为图片)】
iText简介
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.net.MalformedURLException;
- import com.itextpdf.text.Document;
- import com.itextpdf.text.DocumentException;
- import com.itextpdf.text.Element;
- import com.itextpdf.text.Font;
- import com.itextpdf.text.Font.FontFamily;
- import com.itextpdf.text.Image;
- import com.itextpdf.text.PageSize;
- import com.itextpdf.text.Paragraph;
- import com.itextpdf.text.Phrase;
- import com.itextpdf.text.pdf.BaseFont;
- import com.itextpdf.text.pdf.ColumnText;
- import com.itextpdf.text.pdf.PdfContentByte;
- import com.itextpdf.text.pdf.PdfReader;
- import com.itextpdf.text.pdf.PdfStamper;
- import com.itextpdf.text.pdf.PdfWriter;
2、创建PDF文件
- public void createPDF()
- {
- try
- {
- String RESULT = "F:\\java56班\\eclipse-SDK-4.2-win32\\pdfiText.pdf";
- Document document = new Document();
- PdfWriter writer = PdfWriter.getInstance(document,
- new FileOutputStream(RESULT));
- document.open();
- PdfContentByte canvas = writer.getDirectContentUnder();
- writer.setCompressionLevel();
- canvas.saveState(); // q
- canvas.beginText(); // BT
- canvas.moveText(, ); // 36 788 Td
- canvas.setFontAndSize(BaseFont.createFont(), ); // /F1 12 Tf
- // canvas.showText("Hello World"); // (Hello World)Tj
- canvas.showText("你好"); // (Hello World)Tj
- canvas.endText(); // ET
- canvas.restoreState(); // Q
- document.close();
- } catch (FileNotFoundException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (DocumentException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- public void createPDF2()
- {
- try
- {
- String RESULT = "F:\\java56班\\eclipse-SDK-4.2-win32\\pdfiText.pdf";
- Document document = new Document();
- PdfWriter writer = PdfWriter.getInstance(document,
- new FileOutputStream(RESULT));
- document.open();
- writer.setCompressionLevel();
- // Phrase hello = new Phrase("Hello World");
- Phrase hello = new Phrase("你好");
- PdfContentByte canvas = writer.getDirectContentUnder();
- ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, hello, ,
- , );
- document.close();
- } catch (FileNotFoundException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (DocumentException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- public void createPDF3()
- {
- try
- {
- String resource_jpg = "F:\\java56班\\eclipse-SDK-4.2-win32\\1.png";//
- String RESULT = "F:\\java56班\\eclipse-SDK-4.2-win32\\pdfiText.pdf";
- Paragraph p = new Paragraph("Foobar Film Festival", new Font(FontFamily.HELVETICA, ));
- p.setAlignment(Element.ALIGN_CENTER);
- Document document = new Document();//
- PdfWriter writer = PdfWriter.getInstance(document,new FileOutputStream(RESULT));
- document.open();
- document.add(p);
- Image img = Image.getInstance(resource_jpg);
- img.setAbsolutePosition(
- (PageSize.POSTCARD.getWidth() - img.getScaledWidth()) / ,
- (PageSize.POSTCARD.getHeight() - img.getScaledHeight()) / );
- // img.setAbsolutePosition(0, 0);
- document.add(img);
- document.newPage();
- document.add(p);
- document.add(img);
- PdfContentByte over = writer.getDirectContent();
- over.saveState();
- float sinus = (float) Math.sin(Math.PI / );
- float cosinus = (float) Math.cos(Math.PI / );
- BaseFont bf = BaseFont.createFont();
- over.beginText();
- over.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE);
- over.setLineWidth(1.5f);
- over.setRGBColorStroke(0xFF, 0x00, 0x00);
- over.setRGBColorFill(0xFF, 0xFF, 0xFF);
- over.setFontAndSize(bf, );
- over.setTextMatrix(cosinus, sinus, -sinus, cosinus, , );
- over.showText("SOLD OUT");
- over.endText();
- over.restoreState();
- PdfContentByte under = writer.getDirectContentUnder();
- under.saveState();
- under.setRGBColorFill(0xFF, 0xD7, 0x00);
- under.rectangle(, , PageSize.POSTCARD.getWidth() - ,
- PageSize.POSTCARD.getHeight() - );
- under.fill();
- under.restoreState();
- document.close();
- } catch (FileNotFoundException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (DocumentException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (MalformedURLException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
3、在绝对位置插入图片
- public void addImageAbsolu()
- {
- try
- {
- String resource_jpg = "F:\\java56班\\eclipse-SDK-4.2-win32\\1.png";//
- String RESULT = "F:\\java56班\\eclipse-SDK-4.2-win32\\pdfiText.pdf";
- Document document = new Document();
- PdfWriter writer = PdfWriter.getInstance(document,new FileOutputStream(RESULT));
- document.open();
- // PDPage page = (PDPage)doc.getDocumentCatalog().getAllPages().get( 0 );
- Image img = Image.getInstance(resource_jpg);
- img.setAbsolutePosition(
- (PageSize.POSTCARD.getWidth() - img.getScaledWidth()) / ,
- (PageSize.POSTCARD.getHeight() - img.getScaledHeight()) / );
- // img.setAbsolutePosition(0, 0);
- document.add(img);
- document.close();
- } catch (FileNotFoundException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (DocumentException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (MalformedURLException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- public void addImageAbsolu2()
- {
- try
- {
- String resource_jpg = "F:\\java56班\\eclipse-SDK-4.2-win32\\1.png";//
- String result = "F:\\java56班\\eclipse-SDK-4.2-win32\\pdfiText.pdf";
- String result2 = "F:\\java56班\\eclipse-SDK-4.2-win32\\pdfiText2.pdf";
- //创建一个pdf读入流
- PdfReader reader = new PdfReader(result);
- //根据一个pdfreader创建一个pdfStamper.用来生成新的pdf.
- PdfStamper stamper = new PdfStamper(reader,new FileOutputStream(result2));
- //获得pdfstamper在当前页的上层打印内容.也就是说 这些内容会覆盖在原先的pdf内容之上.
- PdfContentByte over = stamper.getOverContent();
- Document document = new Document();
- PdfWriter writer = PdfWriter.getInstance(document,new FileOutputStream(result));
- document.open();
- // PDPage page = (PDPage)doc.getDocumentCatalog().getAllPages().get( 0 );
- Image img = Image.getInstance(resource_jpg);
- img.setAbsolutePosition(, );
- document.add(img);
- document.close();
- } catch (FileNotFoundException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (DocumentException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (MalformedURLException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
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();
- BufferedImage image = page.convertToImage(
- BufferedImage.TYPE_INT_RGB, );
- ImageIOUtil.writeImage(image, "bmp", outputStream, );
- 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文件
- package demo1;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import com.itextpdf.text.Document;
- import com.itextpdf.text.DocumentException;
- import com.itextpdf.text.Image;
- import com.itextpdf.text.Rectangle;
- import com.itextpdf.text.pdf.PdfWriter;
- public class ImgToPDF
- {
- /**
- *
- * @param destPath
- * 生成pdf文件的路劲
- * @param images
- * 需要转换的图片路径的数组
- * @throws IOException
- * @throws DocumentException
- */
- public static void imagesToPdf(String destPath, String imagesPath)
- {
- try
- {
- // 第一步:创建一个document对象。
- Document document = new Document();
- document.setMargins(, , , );
- // 第二步:
- // 创建一个PdfWriter实例,
- PdfWriter.getInstance(document, new FileOutputStream(destPath));
- // 第三步:打开文档。
- document.open();
- // 第四步:在文档中增加图片。
- File files = new File(imagesPath);
- String[] images = files.list();
- int len = images.length;
- for (int i = ; i < len; i++)
- {
- if (images[i].toLowerCase().endsWith(".bmp"))
- {
- String temp = imagesPath + "\\" + images[i];
- Image img = Image.getInstance(temp);
- img.setAlignment(Image.ALIGN_CENTER);
- // 根据图片大小设置页面,一定要先设置页面,再newPage(),否则无效
- document.setPageSize(new Rectangle(img.getWidth(), img
- .getHeight()));
- document.newPage();
- document.add(img);
- }
- }
- // 第五步:关闭文档。
- document.close();
- } catch (Exception e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- public static void main(String[] args)
- {
- String destPath = "F:\\java56班\\eclipse-SDK-4.2-win32\\img\\imagesToPdf.pdf";
- String imagesPath = "F:\\java56班\\eclipse-SDK-4.2-win32\\img\\";
- imagesToPdf(destPath, imagesPath);
- }
- }
2015-01-26
【使用Itext处理PDF文档(新建PDF文件、修改PDF文件、PDF中插入图片、将PDF文件转换为图片)】的更多相关文章
- 【PDF】java使用Itext生成pdf文档--详解
[API接口] 一.Itext简介 API地址:javadoc/index.html:如 D:/MyJAR/原JAR包/PDF/itext-5.5.3/itextpdf-5.5.3-javadoc/ ...
- [.NET开发] C# 合并、拆分PDF文档
在整理文件时,将多个同类型文档合并是实现文档归类的有效方法,也便于文档管理或者文档传输.当然,也可以对一些比较大的文件进行拆分来获取自己想要的部分文档.可以任意地对文档进行合并.拆分无疑为我们了提供极 ...
- 批量将网页转换成图片或PDF文档技巧分享
工作中我们有时要将一些批量的网页转换成图片或者PDF文档格式,尽管多数浏览器具有滚动截屏或者打印输出PDF文档功能.可是假设有几十上百张网页须要处理,那也是要人命的.所以我一直想找一款可以批量处理该工 ...
- C# 复制PDF页面到另一个PDF文档
C# 复制PDF页面到另一个PDF文档 有时候我们可能有这样一个需求,那就是把PDF页面从一个PDF文档复制到另一个PDF文档中.由于PDF文档并不像word文档那样好编辑,因此复制也相对没有那么容易 ...
- Java使用Flying Saucer实现HTML代码生成PDF文档
1.需要的jar包:org.xhtmlrenderer.flying-saucer-pdf-itext5,Maven依赖如下: <dependency> <groupId>or ...
- CentOS6.4下使用默认的文档查看器打开PDF文档乱码的解决方案
最近在CentOS6.4下使用其默认的文档查看器打开PDF文档时出现乱码的方块,有两种方法可以解决. 方法一:修改/etc/fonts/conf.d/49-sansserif.conf文件,如 ...
- 使用Spire PDF for .NET将HTML转换成PDF文档
目录 开发环境说明 Spire PDF for .NET (free edition)体验 资源下载 开发环境说明 Microsoft Visual Studio 2013 Ultimate Edit ...
- C# 打印PDF文档的10种方法
操作PDF文档时,打印是常见的需求之一.针对不同的打印需求,可分多种情况来进行,如设置静默打印.指定打印页码范围和打印纸张大小.双面打印.黑白打印等等.经过测试,下面将对常见的几种PDF打印需求做一些 ...
- 根据传入的文件名称动态从moglifs图片服务器拿到pdf文档并在线浏览
1.通过百度编辑器上传pdf文档等附件时,在上传方法中将返回的url进行设定,以达到后期点击后可进行浏览的效果: public static final State save(HttpServletR ...
- java实现在线浏览PDF文档功能
实现在线浏览pdf文档功能(本代码适用于项目服务中固定的并且少量的pdf浏览,比如注册时的注册条款在线浏览等): //设置响应内容类型为PDF类型 response.setContentType(&q ...
随机推荐
- 关于oracle数据库(3)
show user ; 查看当前用户的名称 select * from tab; 查看当前用户有哪些表 删除用户 drop user jky cascade; //cascade; 意思是级联操作 ...
- npm常用指令
安装: npm install <name> npm install <name> 安装依赖包,默认安装最新版本,也可在后面加上版本号,并且将安装信息加入项目的package. ...
- angular中重要指令介绍($eval,$parse和$compile)
在angular的服务中,有一些服务你不得不去了解,因为他可以说是ng的核心,而今天,我要介绍的就是ng的两个核心服务,$parse和$compile.其实这两个服务讲的人已经很多了,但是100个读者 ...
- 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 ...
- Ubuntu 12.04 中自定义DNS服务器设置
首先我们需要创建一个文件/etc/resolvconf/resolv.conf.d/tail: #vim /etc/resolvconf/resolv.conf.d/tail 然后我们在这个文件里写入 ...
- 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 ...
- VMware中Ubuntu 14.04出现Unknown Display问题解决
如需转载请标明出处:http://blog.csdn.net/itas109 QQ技术交流群:129518033 今天安装完Ubuntu 14.04后,在虚拟机中显示不全,本来调节一下屏幕分辨率就可以 ...
- MVC 数据绑定
在做Asp.Net MVC项目中,都知道View负责页面展示数据或者提供页面收集数据,而所展示的数据或者收集的数据都是从Controller的Action中获取或提交到Controller的Actio ...
- Entity FrameWork 实体属性为decimal时默认只保存2位小数
问题描述:当采用EF的DbContext保存decimal类型数据到数据库,默认只会保存小数点后的前2位小数,其余均置0:例如保存101.182352152322,实际存到数据库里的数据为101.18 ...
- C/C++时间函数的使用
来源:http://blog.csdn.net/apull/article/details/5379819 一.获取日历时间time_t是定义在time.h中的一个类型,表示一个日历时间,也就是从19 ...