iText 是java和C#中的一个处理PDF的开源类库,国外的大牛已经把它移植到Android上了,但是直接拿来用还是需要花费一点功夫,下面就用一个简单的demo来测试一下。

iText项目地址:https://code.google.com/p/droidtext/

首先用过svn把代码check下来。

得到三个文件夹,droidText是一个android的库工程,droidTextTest是测试工程。

在eclipse中导入droidText项目。这是个library project,后面创建的项目需要引用到。

然后创建一个Android工程-iTextTest

在工程中引用droidText:

Project->properties->Android->LIbrary:ADD

链接好之后就像上图。

主界面就一个Button,按下之后就开始生产PDF。

package com.example.itexttest;import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;
import java.lang.reflect.Method;import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;public class ITextActivity extends Activity {private Button mButton;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_itext);mButton = (Button)findViewById(R.id.button1);mButton.setOnClickListener(new OnClickListenerImpl());}private class OnClickListenerImpl implements View.OnClickListener{@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stub//Toast.makeText(getApplicationContext(), "Run", Toast.LENGTH_SHORT).show();// Create droidtext directory for storing resultsFile file = new File(android.os.Environment.getExternalStorageDirectory()+ File.separator + "iTextTest");if (!file.exists()) {file.mkdir();}System.out.println("Click!");Thread t = new Thread() {public void run() {int success = 0;int count = 1;String className = "com.example.itexttest.HelloWprld";String result = null;try {// Set output streams to bytearray streams so we can// display the output of examplesByteArrayOutputStream bos = new ByteArrayOutputStream();PrintStream errorStream = new PrintStream(bos, true);System.setErr(errorStream);ByteArrayOutputStream bos2 = new ByteArrayOutputStream();PrintStream outStream = new PrintStream(bos2, true);System.setOut(outStream);// Find the main methodClass<!--?--> c = Class.forName(className);Method main = c.getDeclaredMethod("main",String[].class);System.out.println("GetMain"+main.getName());// Emulate CLI parameters if necessaryString[] params = null;if (className.equals("com.lowagie.examples.objects.tables.pdfptable.FragmentTable")) {params = new String[] { "3" };} else if (className.equals("com.lowagie.examples.objects.images.tiff.OddEven")) {params = new String[] { "odd.tif", "even.tif","odd_even.tiff" };} else if (className.equals("com.lowagie.examples.objects.images.tiff.Tiff2Pdf")) {params = new String[] { "tif_12.tif" };} else if (className.equals("com.lowagie.examples.objects.images.DvdCover")) {params = new String[] { "dvdcover.pdf", "Title","0xff0000", "hitchcock.png" };} else if (className.equals("com.lowagie.examples.forms.ListFields")) {params = new String[] {};} else if (className.equals("com.lowagie.examples.general.read.Info")) {params = new String[] { "RomeoJuliet.pdf" };} else if (className.equals("com.lowagie.examples.objects.anchors.OpenApplication")) {params = new String[] { "" };}main.invoke(null, (Object) params);// Parse resultsString string = new String(bos.toByteArray());String string2 = new String(bos2.toByteArray());if (string.length() > 0) {result = "Failed: " + string;} else if (string2.contains("Exception")) {result = "Failed: " + string2;} else if ("Images.pdf" != null) {File pdf = new File(Environment.getExternalStorageDirectory()+ File.separator + "iTextTest"+ File.separator+ "Images.pdf");System.out.println("Create Pdf@");if (!pdf.exists()) {result = "Failed: Resulting pdf didn't get created";} else if (pdf.length() <= 0) {result = "Failed: Resulting pdf is empty";} else {success++;result = "Successful";}} else {success++;result = "Successful";}} catch (Exception e) {result = "Failed with exception: "+ e.getClass().getName() + ": "+ e.getMessage();System.out.println(result);}if (result.startsWith("Failed")) {System.out.println("Failed!");} else {System.out.println("Success!");}System.out.println(result);}};t.start();}}}

OnClick里面的代码有点小复杂,要用的的话直接粘就可以了,注意修改相应的变量名,classname对应对就是操作itext生产pdf的类。

在包里面再创建两个测试类:

HelloWorld.java

package com.example.itexttest;import java.io.FileOutputStream;
import java.io.IOException;import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;/*** Generates a simple 'Hello World' PDF file.* * @author blowagie*/public class HelloWorld {/*** Generates a PDF file with the text 'Hello World'* * @param args*            no arguments needed here*/public static void main(String[] args) {System.out.println("Hello World");// step 1: creation of a document-objectDocument document = new Document();try {// step 2:// we create a writer that listens to the document// and directs a PDF-stream to a filePdfWriter.getInstance(document, new FileOutputStream(android.os.Environment.getExternalStorageDirectory() + java.io.File.separator + "iTextTest" + java.io.File.separator + "HelloWorld.pdf"));// step 3: we open the documentdocument.open();// step 4: we add a paragraph to the documentdocument.add(new Paragraph("Hello World"));} catch (DocumentException de) {System.err.println(de.getMessage());} catch (IOException ioe) {System.err.println(ioe.getMessage());}// step 5: we close the documentdocument.close();}
}

生产Pdf如下:

Rotating.java(创建图片,并旋转)

注意再sdcard的根目录里面放一张图片,改名jxk_run.png。

/** $Id: Rotating.java 3373 2008-05-12 16:21:24Z xlv $** This code is part of the 'iText Tutorial'.* You can find the complete tutorial at the following address:* http://itextdocs.lowagie.com/tutorial/** This code is distributed in the hope that it will be useful,* but WITHOUT ANY WARRANTY; without even the implied warranty of* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.** itext-questions@lists.sourceforge.net*/
package com.example.itexttest;import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import com.example.itexttest.R;
import com.example.itexttest.ITextActivity;import android.graphics.Bitmap;
import android.graphics.BitmapFactory;import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Image;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;/*** Rotating images.*/
public class Rotating {/*** Rotating images.* * @param args*            No arguments needed*/public static void main(String[] args) {System.out.println("Rotating an Image");// step 1: creation of a document-objectDocument document = new Document();try {// step 2:// we create a writer that listens to the document// and directs a PDF-stream to a filePdfWriter.getInstance(document, new FileOutputStream(android.os.Environment.getExternalStorageDirectory() + java.io.File.separator +  "iTextTest"  + java.io.File.separator + "rotating.pdf"));// step 3: we open the documentdocument.open();// step 4: we add content//Can't use filename => use byte[] instead
//          Image jpg4 = Image.getInstance("otsoe.jpg");ByteArrayOutputStream stream = new ByteArrayOutputStream();//Bitmap bitmap = BitmapFactory.decodeResource(ITextActivity.getActivity().getResources(), R.drawable.otsoe);Bitmap bitmap = BitmapFactory.decodeFile("/mnt/sdcard/jxk_run.png");bitmap.compress(Bitmap.CompressFormat.JPEG /* FileType */,100 /* Ratio */, stream);Image jpg = Image.getInstance(stream.toByteArray());jpg.setAlignment(Image.MIDDLE);jpg.setRotation((float) Math.PI / 6);document.add(new Paragraph("rotate 30 degrees"));document.add(jpg);document.newPage();jpg.setRotation((float) Math.PI / 4);document.add(new Paragraph("rotate 45 degrees"));document.add(jpg);document.newPage();jpg.setRotation((float) Math.PI / 2);document.add(new Paragraph("rotate pi/2 radians"));document.add(jpg);document.newPage();jpg.setRotation((float) (Math.PI * 0.75));document.add(new Paragraph("rotate 135 degrees"));document.add(jpg);document.newPage();jpg.setRotation((float) Math.PI);document.add(new Paragraph("rotate pi radians"));document.add(jpg);document.newPage();jpg.setRotation((float) (2.0 * Math.PI));document.add(new Paragraph("rotate 2 x pi radians"));document.add(jpg);} catch (DocumentException de) {System.err.println(de.getMessage());} catch (IOException ioe) {System.err.println(ioe.getMessage());}// step 5: we close the documentdocument.close();}}

生产PDF如下:

在Android中利用iText生成PDF相关推荐

  1. 利用iText生成pdf报表

    任务书.期中检查.延期申请书 一.    需要用到的支持 包支持:向java工程导入两个包 iText.jar,iTextAsian.jar(汉字支持包) 软件支持:Adobe Acrobat Pro ...

  2. wps制作pdf模板,Adobe Acrobat DC利用pdf模板做填充数据表单域,在maven项目中利用java生成pdf

    如做pdf建议http://www.xdocin.com/index.html 以下方法仅供参考 首先制作一个pdf模板: 1.先用word做出模板界面 2.文件另存为pdf格式文件 3.通过Adob ...

  3. java中利用itext编辑pdf

    最近项目需要,在调研如何在pdf中增加标识字样,用来区分版本.最后确定用itext来实现. itext的官网是:http://www.itextpdf.com/ 代码如下: Java代码   /** ...

  4. java 修改pdf_java中利用itext编辑pdf

    最近项目需要,在调研如何在pdf中增加标识字样,用来区分版本.最后确定用itext来实现. itext的官网是:http://www.itextpdf.com/ 代码如下: Java代码 /** * ...

  5. java操作跨页的word cell,利用itext 生成pdf,处理cell 跨页问题 [转]

    处理方法: PdfPTable table =newPdfPTable(1); table.setSplitLate(false); table.setSplitRows(true); 开发中的例子: ...

  6. 利用velocity模板以及itext生成pdf

    利用velocity模板以及itext生成pdf 我整理的源码:http://download.csdn.net/download/u012174571/8748897 首先是velocity的使用: ...

  7. android pdfjet_GitHub - lnj721/PdfBuilder: Android端使用图片生成PDF文件

    PdfBuilder Android端使用图片生成PDF文件 一.应用场景 从本地选择图片生成pdf文件,由于Android本身并没有对pdf的支持,这里选择使用一个第三方的库来达成需求. 二.库的选 ...

  8. iText生成pdf文书

    我们项目需要生成文书,文书内容比较麻烦,需要动态插入表格.图片.修改字体颜色等. 首先理所当然的使用了word方式,在浏览器中使用NTKO生成word,动态替换标签文字,插入表格,虽然实现了功能,但是 ...

  9. 利用itext操作pdf从数据库导出大量数据--添加水印(四)

    [原始需求] 通过SQL及JDBC模式导出各类业务数据,以PDF文件格式存放,要求该文件只能查看和打印(不能编辑和篡改),文件要有公司相关标志和水印功能. [需求分析] 1. 通过SQL及JDBC模式 ...

最新文章

  1. python json.loads()中文问题-python处理json数据中的中文
  2. PyCharm配置anaconda环境 安装第三方库
  3. 两个经典的Oracle触发器示例
  4. ubuntu使用apt-get时出现could not get lock怎么解决
  5. 修改url 参数_SEO优化设计,如何处理网址的动态参数?
  6. unity如何得到所有子对象_Unity3D研究院之自动计算所有子对象包围盒(六)
  7. 这 8款开源思维导图工具真的很神奇【程序员必备学习工具】
  8. Hitool工具烧写程序(按分区烧写)
  9. 数据结构面试题以及答案整理
  10. 名师李涛老师主讲 Photoshop CS2 (全教程下载)
  11. 淘宝客微信发单机器人_返利机器人快速开发SDK
  12. 为什么苹果日历不能设置日程_苹果自带日历hold每日待办日程提醒不再轻易miss日程...
  13. 【报错】paddle相关报错和处理方法
  14. jdk8新特性-Lambda表达式,方法引用
  15. 力扣第235题“二叉搜索树的最近公共先祖”的解题思路
  16. 怎么压缩图片200k以下?
  17. 【Python_PyQtGraph 学习笔记(五)】基于PyQtGraph和GraphicsLayoutWidget动态绘图并实现窗口模式,且保留全部绘图信息
  18. 美年旅游_跟团游_编辑跟团游
  19. Windows系统命令行安装软件的几种方式
  20. Launcher 快捷方式、文件夹等的默认设置

热门文章

  1. 我来做百科(第二十天) C
  2. android AIDL 入门讲解非常好的文章(网页代码着色给力)
  3. linux SHELL下替代sed、ask的常用字符串处理(截取,判断、替换)
  4. CSS垂直居中的方法
  5. Timer的schedule和scheduleAtFixedRate方法的区别解析(转)
  6. Exchange 2013 创建新用户
  7. 如何在一个日期值上加上分钟值得到新的日期
  8. 令人惊奇的FLEX 3D UI.
  9. B站智能防挡弹幕的一种python实现
  10. haproxy基于cookie实现会话绑定