Android中生成PDF

来源:互联网 发布:2016软件学院排名 编辑:程序博客网 时间:2024/05/29 11:19

 


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

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

首先用过svn把代码check下来,终端运行

svn checkout http://droidtext.googlecode.com/svn/trunk/ droidtext-read-only



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


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


然后创建一个Android工程-iTextTest

在工程中引用droidText:

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



链接好之后就像上图。


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

[java] view plaincopyprint?
  1. package com.example.itexttest;  
  2.   
  3. import java.io.ByteArrayOutputStream;  
  4. import java.io.File;  
  5. import java.io.PrintStream;  
  6. import java.lang.reflect.Method;  
  7.   
  8. import android.os.Bundle;  
  9. import android.os.Environment;  
  10. import android.app.Activity;  
  11. import android.view.Menu;  
  12. import android.view.View;  
  13. import android.widget.Button;  
  14. import android.widget.Toast;  
  15.   
  16. public class ITextActivity extends Activity {  
  17.     private Button mButton;  
  18.   
  19.     @Override  
  20.     protected void onCreate(Bundle savedInstanceState) {  
  21.         super.onCreate(savedInstanceState);  
  22.         setContentView(R.layout.activity_itext);  
  23.         mButton = (Button)findViewById(R.id.button1);  
  24.         mButton.setOnClickListener(new OnClickListenerImpl());  
  25.     }  
  26.   
  27.     private class OnClickListenerImpl implements View.OnClickListener  
  28.     {  
  29.   
  30.         @Override  
  31.         public void onClick(View arg0) {  
  32.             // TODO Auto-generated method stub  
  33.             //Toast.makeText(getApplicationContext(), "Run", Toast.LENGTH_SHORT).show();  
  34.             // Create droidtext directory for storing results  
  35.             File file = new File(  
  36.                     android.os.Environment.getExternalStorageDirectory()  
  37.                     + File.separator + "iTextTest");  
  38.             if (!file.exists()) {  
  39.                 file.mkdir();  
  40.             }  
  41.             System.out.println("Click!");  
  42.   
  43.             Thread t = new Thread() {  
  44.   
  45.                 public void run() {  
  46.                     int success = 0;  
  47.                     int count = 1;  
  48.                     String className = "com.example.itexttest.HelloWprld";  
  49.   
  50.                     String result = null;  
  51.                     try {  
  52.                         // Set output streams to bytearray streams so we can  
  53.                         // display the output of examples  
  54.                         ByteArrayOutputStream bos = new ByteArrayOutputStream();  
  55.                         PrintStream errorStream = new PrintStream(bos, true);  
  56.                         System.setErr(errorStream);  
  57.   
  58.                         ByteArrayOutputStream bos2 = new ByteArrayOutputStream();  
  59.                         PrintStream outStream = new PrintStream(bos2, true);  
  60.                         System.setOut(outStream);  
  61.   
  62.                         // Find the main method  
  63.                         Class<?> c = Class.forName(className);  
  64.                         Method main = c.getDeclaredMethod("main",String[].class);  
  65.                         System.out.println("GetMain"+main.getName());  
  66.   
  67.                         // Emulate CLI parameters if necessary  
  68.                         String[] params = null;  
  69.                         if (className  
  70.                                 .equals("com.lowagie.examples.objects.tables.pdfptable.FragmentTable")) {  
  71.                             params = new String[] { "3" };  
  72.                         } else if (className  
  73.                                 .equals("com.lowagie.examples.objects.images.tiff.OddEven")) {  
  74.                             params = new String[] { "odd.tif""even.tif",  
  75.                             "odd_even.tiff" };  
  76.                         } else if (className  
  77.                                 .equals("com.lowagie.examples.objects.images.tiff.Tiff2Pdf")) {  
  78.                             params = new String[] { "tif_12.tif" };  
  79.                         } else if (className  
  80.                                 .equals("com.lowagie.examples.objects.images.DvdCover")) {  
  81.                             params = new String[] { "dvdcover.pdf""Title",  
  82.                                     "0xff0000""hitchcock.png" };  
  83.                         } else if (className  
  84.                                 .equals("com.lowagie.examples.forms.ListFields")) {  
  85.                             params = new String[] {};  
  86.                         } else if (className  
  87.                                 .equals("com.lowagie.examples.general.read.Info")) {  
  88.                             params = new String[] { "RomeoJuliet.pdf" };  
  89.                         } else if (className  
  90.                                 .equals("com.lowagie.examples.objects.anchors.OpenApplication")) {  
  91.                             params = new String[] { "" };  
  92.                         }  
  93.   
  94.                         main.invoke(null, (Object) params);  
  95.   
  96.                         // Parse results  
  97.                         String string = new String(bos.toByteArray());  
  98.                         String string2 = new String(bos2.toByteArray());  
  99.                         if (string.length() > 0) {  
  100.                             result = "Failed: " + string;  
  101.                         } else if (string2.contains("Exception")) {  
  102.                             result = "Failed: " + string2;  
  103.                         } else if ("Images.pdf" != null) {  
  104.                             File pdf = new File(  
  105.                                     Environment.getExternalStorageDirectory()  
  106.                                     + File.separator + "iTextTest"  
  107.                                     + File.separator  
  108.                                     + "Images.pdf");  
  109.                             System.out.println("Create Pdf@");  
  110.                             if (!pdf.exists()) {  
  111.                                 result = "Failed: Resulting pdf didn't get created";  
  112.                             } else if (pdf.length() <= 0) {  
  113.                                 result = "Failed: Resulting pdf is empty";  
  114.                             } else {  
  115.                                 success++;  
  116.                                 result = "Successful";  
  117.                             }  
  118.                         } else {  
  119.                             success++;  
  120.                             result = "Successful";  
  121.                         }  
  122.                     } catch (Exception e) {  
  123.                         result = "Failed with exception: "  
  124.                                 + e.getClass().getName() + ": "  
  125.                                 + e.getMessage();  
  126.                         System.out.println(result);  
  127.                     }  
  128.                     if (result.startsWith("Failed")) {  
  129.                         System.out.println("Failed!");  
  130.                     } else {  
  131.                         System.out.println("Success!");  
  132.                     }  
  133.                     System.out.println(result);  
  134.                 }  
  135.   
  136.             };  
  137.             t.start();  
  138.         }  
  139.   
  140.     }  
  141.   
  142. }  

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


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

HelloWorld.java

[java] view plaincopyprint?
  1. package com.example.itexttest;  
  2.   
  3. import java.io.FileOutputStream;  
  4. import java.io.IOException;  
  5.   
  6. import com.lowagie.text.Document;  
  7. import com.lowagie.text.DocumentException;  
  8. import com.lowagie.text.Paragraph;  
  9. import com.lowagie.text.pdf.PdfWriter;  
  10.   
  11. /** 
  12.  * Generates a simple 'Hello World' PDF file. 
  13.  *  
  14.  * @author blowagie 
  15.  */  
  16.   
  17. public class HelloWorld {  
  18.   
  19.         /** 
  20.          * Generates a PDF file with the text 'Hello World' 
  21.          *  
  22.          * @param args 
  23.          *            no arguments needed here 
  24.          */  
  25.         public static void main(String[] args) {  
  26.   
  27.                 System.out.println("Hello World");  
  28.   
  29.                 // step 1: creation of a document-object  
  30.                 Document document = new Document();  
  31.                 try {  
  32.                         // step 2:  
  33.                         // we create a writer that listens to the document  
  34.                         // and directs a PDF-stream to a file  
  35.                         PdfWriter.getInstance(document, new FileOutputStream(android.os.Environment.getExternalStorageDirectory() + java.io.File.separator + "iTextTest" + java.io.File.separator + "HelloWorld.pdf"));  
  36.   
  37.                         // step 3: we open the document  
  38.                         document.open();  
  39.                         // step 4: we add a paragraph to the document  
  40.                         document.add(new Paragraph("Hello World"));  
  41.                 } catch (DocumentException de) {  
  42.                         System.err.println(de.getMessage());  
  43.                 } catch (IOException ioe) {  
  44.                         System.err.println(ioe.getMessage());  
  45.                 }  
  46.   
  47.                 // step 5: we close the document  
  48.                 document.close();  
  49.         }  
  50. }  

生产Pdf如下:


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

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

[java] view plaincopyprint?
  1. /* 
  2.  * $Id: Rotating.java 3373 2008-05-12 16:21:24Z xlv $ 
  3.  * 
  4.  * This code is part of the 'iText Tutorial'. 
  5.  * You can find the complete tutorial at the following address: 
  6.  * http://itextdocs.lowagie.com/tutorial/ 
  7.  * 
  8.  * This code is distributed in the hope that it will be useful, 
  9.  * but WITHOUT ANY WARRANTY; without even the implied warranty of 
  10.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
  11.  * 
  12.  * itext-questions@lists.sourceforge.net 
  13.  */  
  14. package com.example.itexttest;  
  15.   
  16. import java.io.ByteArrayOutputStream;  
  17. import java.io.FileOutputStream;  
  18. import java.io.IOException;  
  19. import com.example.itexttest.R;  
  20. import com.example.itexttest.ITextActivity;  
  21.   
  22. import android.graphics.Bitmap;  
  23. import android.graphics.BitmapFactory;  
  24.   
  25. import com.lowagie.text.Document;  
  26. import com.lowagie.text.DocumentException;  
  27. import com.lowagie.text.Image;  
  28. import com.lowagie.text.Paragraph;  
  29. import com.lowagie.text.pdf.PdfWriter;  
  30.   
  31. /** 
  32.  * Rotating images. 
  33.  */  
  34. public class Rotating {  
  35.     /** 
  36.      * Rotating images. 
  37.      *  
  38.      * @param args 
  39.      *            No arguments needed 
  40.      */  
  41.     public static void main(String[] args) {  
  42.   
  43.         System.out.println("Rotating an Image");  
  44.   
  45.         // step 1: creation of a document-object  
  46.         Document document = new Document();  
  47.   
  48.         try {  
  49.   
  50.             // step 2:  
  51.             // we create a writer that listens to the document  
  52.             // and directs a PDF-stream to a file  
  53.   
  54.             PdfWriter.getInstance(document, new FileOutputStream(android.os.Environment.getExternalStorageDirectory() + java.io.File.separator +  "iTextTest"  + java.io.File.separator + "rotating.pdf"));  
  55.   
  56.             // step 3: we open the document  
  57.             document.open();  
  58.   
  59.             // step 4: we add content  
  60.             //Can't use filename => use byte[] instead  
  61. //          Image jpg4 = Image.getInstance("otsoe.jpg");  
  62.             ByteArrayOutputStream stream = new ByteArrayOutputStream();  
  63.             //Bitmap bitmap = BitmapFactory.decodeResource(ITextActivity.getActivity().getResources(), R.drawable.otsoe);  
  64.             Bitmap bitmap = BitmapFactory.decodeFile("/mnt/sdcard/jxk_run.png");  
  65.             bitmap.compress(Bitmap.CompressFormat.JPEG /* FileType */,100 /* Ratio */, stream);  
  66.             Image jpg = Image.getInstance(stream.toByteArray());  
  67.             jpg.setAlignment(Image.MIDDLE);  
  68.   
  69.             jpg.setRotation((float) Math.PI / 6);  
  70.             document.add(new Paragraph("rotate 30 degrees"));  
  71.             document.add(jpg);  
  72.             document.newPage();  
  73.   
  74.             jpg.setRotation((float) Math.PI / 4);  
  75.             document.add(new Paragraph("rotate 45 degrees"));  
  76.             document.add(jpg);  
  77.             document.newPage();  
  78.   
  79.             jpg.setRotation((float) Math.PI / 2);  
  80.             document.add(new Paragraph("rotate pi/2 radians"));  
  81.             document.add(jpg);  
  82.             document.newPage();  
  83.   
  84.             jpg.setRotation((float) (Math.PI * 0.75));  
  85.             document.add(new Paragraph("rotate 135 degrees"));  
  86.             document.add(jpg);  
  87.             document.newPage();  
  88.   
  89.             jpg.setRotation((float) Math.PI);  
  90.             document.add(new Paragraph("rotate pi radians"));  
  91.             document.add(jpg);  
  92.             document.newPage();  
  93.   
  94.             jpg.setRotation((float) (2.0 * Math.PI));  
  95.             document.add(new Paragraph("rotate 2 x pi radians"));  
  96.             document.add(jpg);  
  97.         } catch (DocumentException de) {  
  98.             System.err.println(de.getMessage());  
  99.         } catch (IOException ioe) {  
  100.             System.err.println(ioe.getMessage());  
  101.         }  
  102.   
  103.         // step 5: we close the document  
  104.         document.close();  
  105.     }  
  106.   
  107. }  

生产PDF如下:

1 0
原创粉丝点击