【使用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 ...
随机推荐
- tableView左滑按钮
- (nullable NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsFo ...
- JQuery_图片未加载!
JQuery_图片未加载! <html> <head> <script type="text/javascript" src="/jquer ...
- leetcode83,删除有序链表中的重复元素
Given a sorted linked list, delete all duplicates such that each element appear only once. For examp ...
- data Mining with Weka: Trailer More Data Mining with Weka 用weka 进行数据挖掘 Weka 用weka 进行更多数据挖掘
https://www.youtube.com/user/WekaMOOC 大学公开课 视频教程 weka 入门教程 data Mining with Weka: Trailer More Dat ...
- Educational Codeforces Round 15_D. Road to Post Office
D. Road to Post Office time limit per test 1 second memory limit per test 256 megabytes input standa ...
- 开发MOSS自定义字段类型
前段时间,由于刚好项目定制的需要,笔者就开发了几个自定义字段类型.在这抽空做个详细笔记,方便初学者学习.这方面的资料也很多,如果自身觉得不大明白可以参考下SDK和网上的相关文章.本章的目的主要是给新手 ...
- flash cs6 更新到Flash player15.0 及Air 更新方法
1.自行下载Air 15.0 sdk (Flash player 包含在内) 2. 到15.0Air 包 里找player :AIR15.0\frameworks\libs\player 里面有pl ...
- ASP.NET多文件批量打包下载
在对多文件打包中用到了 DotNetZip 的方法来实现对多文件压缩打包.需要到http://dotnetzip.codeplex.com/处下载该文件,然后引用即可. Default.aspx: & ...
- 贾扬清分享_深度学习框架caffe
Caffe是一个清晰而高效的深度学习框架,其作者是博士毕业于UC Berkeley的 贾扬清,目前在Google工作.本文是根据机器学习研究会组织的online分享的交流内容,简单的整理了一下. 目录 ...
- Docker学习笔记 — Docker私有仓库搭建【转载】
标签: Docker 2015-03-10 21:08 24190人阅读 评论(0) 收藏 举报 分类: Docker(26) 目录(?)[+] 和Mavan的管理一样,Dockers不仅 ...