iText简介
iText是著名的开放源码的站点sourceforge一个项目,是用于生成PDF文档的一个java类库。通过iText不仅可以生成PDF或rtf的文档,而且可以将XML、Html文件转化为PDF文件。 iText的安装非常方便,下载iText.jar文件后,只需要在系统的CLASSPATH中加入iText.jar的路径,在程序中就可以使用iText类库了。
1、包的引用
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