在Android中利用iText生成PDF

jopen 12年前發布 | 70K 次閱讀 Android Android開發 移動開發

iText 是java和C#中的一個處理PDF的開源類庫,國外的大牛已經把它移植到Android上了,但是直接拿來用還是需要花費一點功夫,下面就用一個簡單的demo來測試一下。

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

首先用過svn把代碼check下來。

在Android中利用iText生成PDF

 

得到三個文件夾,droidText是一個android的庫工程,droidTextTest是測試工程。

 

在eclipse中導入droidText項目。這是個library project,后面創建的項目需要引用到。

 

然后創建一個Android工程-iTextTest

在工程中引用droidText:

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

在Android中利用iText生成PDF

 

鏈接好之后就像上圖。

 

主界面就一個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;

    @Override
    protected 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
    {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            //Toast.makeText(getApplicationContext(), "Run", Toast.LENGTH_SHORT).show();
            // Create droidtext directory for storing results
            File 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 examples
                        ByteArrayOutputStream 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 method
                        Class c = Class.forName(className);
                        Method main = c.getDeclaredMethod("main",String[].class);
                        System.out.println("GetMain"+main.getName());

                        // Emulate CLI parameters if necessary
                        String[] 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 results
                        String 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-object
                Document document = new Document();
                try {
                        // step 2:
                        // we create a writer that listens to the document
                        // and directs a PDF-stream to a file
                        PdfWriter.getInstance(document, new FileOutputStream(android.os.Environment.getExternalStorageDirectory() + java.io.File.separator + "iTextTest" + java.io.File.separator + "HelloWorld.pdf"));

                        // step 3: we open the document
                        document.open();
                        // step 4: we add a paragraph to the document
                        document.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 document
                document.close();
        }
}

生產Pdf如下:

在Android中利用iText生成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-object
        Document document = new Document();

        try {

            // step 2:
            // we create a writer that listens to the document
            // and directs a PDF-stream to a file

            PdfWriter.getInstance(document, new FileOutputStream(android.os.Environment.getExternalStorageDirectory() + java.io.File.separator +  "iTextTest"  + java.io.File.separator + "rotating.pdf"));

            // step 3: we open the document
            document.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 document
        document.close();
    }

}

生產PDF如下:

在Android中利用iText生成PDF

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!