在Android应用程序中创建,编写和显示PDF文件

时间:2015-04-29 11:06:01

标签: android pdf itext

我有一个Android应用程序,它基本上是一个接受用户输入的表单。此输入存储在数据库中。但是我想用用户输入的信息创建一个pdf文件并显示它,以便用户可以打印文件或将文件保存到他们的Android注释选项卡。什么是最好的方法。我见过iText,但这不会呈现文件。我在网上找到了这个代码,我测试了它以了解pdf创建的概念。这使用了Lowagie 2.1.7

    package com.example.sweetiean.androidpdfdemo;

        import android.content.Intent;
        import android.graphics.Bitmap;
        import android.graphics.BitmapFactory;
        import android.graphics.Color;
        import android.net.Uri;
        import android.os.Environment;
        import android.support.v7.app.ActionBarActivity;
        import android.os.Bundle;
        import android.util.Log;
        import android.view.Menu;
        import android.view.MenuItem;
        import android.view.View;
        import android.widget.Button;
        import android.widget.Toast;

        import com.lowagie.text.Document;
        import com.lowagie.text.DocumentException;
        import com.lowagie.text.Font;
        import com.lowagie.text.HeaderFooter;
        import com.lowagie.text.Paragraph;
        import com.lowagie.text.Phrase;
        import com.lowagie.text.pdf.PdfWriter;
        import com.lowagie.text.Image;


        import java.io.ByteArrayOutputStream;
        import java.io.File;
        import java.io.FileOutputStream;
        import java.io.IOException;




    public class MainActivity extends ActionBarActivity {

    private Button createPDF , openPDF;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        createPDF = (Button)findViewById(R.id.button1);
        createPDF.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                createPDF();
            }
        });

        openPDF = (Button)findViewById(R.id.button2);
        openPDF.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                openPdf();
            }
        });
    }

    public void createPDF()
    {
        Document doc = new Document();

        try {
            String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/PDF";

            File dir = new File(path);
            if(!dir.exists())
                dir.mkdirs();

            Log.d("PDFCreator", "PDF Path: " + path);

            File file = new File(dir, "demo.pdf");
            FileOutputStream fOut = new FileOutputStream(file);

            PdfWriter.getInstance(doc, fOut);

            //open the document
            doc.open();

          /* Create Paragraph and S`enter code here`et Font */
            Paragraph p1 = new Paragraph("Hi! I am Generating my first PDF using DroidText");

   /* Create Set Font and its Size */
            Font paraFont= new Font(Font.HELVETICA);
            paraFont.setSize(16);
            p1.setAlignment(Paragraph.ALIGN_CENTER);
            p1.setFont(paraFont);

            //add paragraph to document
            doc.add(p1);


            Paragraph p2 = new Paragraph("This is an example of a simple paragraph");

  /* You can also SET FONT and SIZE like this */
            Font paraFont2= new Font(Font.COURIER,14.0f, Color.GREEN);
            p2.setAlignment(Paragraph.ALIGN_CENTER);
            p2.setFont(paraFont2);

            doc.add(p2);

   /* Inserting Image in PDF */
            /*ByteArrayOutputStream stream = new ByteArrayOutputStream();
            Bitmap bitmap = BitmapFactory.decodeResource(getBaseContext().getResources(), R.drawable.android);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100 , stream);
            Image myImg = Image.getInstance(stream.toByteArray());
            myImg.setAlignment(Image.MIDDLE);

            //add image to document
            doc.add(myImg);*/

            //set footer
            Phrase footerText = new Phrase("This is an example of a footer");
            HeaderFooter pdfFooter = new HeaderFooter(footerText, false);
            doc.setFooter(pdfFooter);

            Toast.makeText(getApplicationContext(), "Created...", Toast.LENGTH_LONG).show();

        } catch (DocumentException de) {
            Log.e("PDFCreator", "DocumentException:" + de);
        } catch (IOException e) {
            Log.e("PDFCreator", "ioException:" + e);
        }
        finally
        {
            doc.close();
        }
    }

    void openPdf()
    {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/PDF";

        File file = new File(path, "demo.pdf");

        intent.setDataAndType( Uri.fromFile(file), "application/pdf" );
        startActivity(intent);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

这是主要活动。

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<Button
    android:id="@+id/button2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textView1"
    android:layout_marginTop="100dp"
    android:text="Open PDF" />

<Button
    android:id="@+id/button1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/textView1"
    android:layout_marginTop="44dp"
    android:text="Generate PDF" />

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="50dp"
    android:text="@string/hello_world" />

3 个答案:

答案 0 :(得分:1)

选中此link,它要求您下载一个jar文件。(链接中的更多说明)。这是生成pdf的代码的一部分。

package com.cete.androidexamples.dynamicpdf.helloworld;

import com.cete.dynamicpdf.*;
import com.cete.dynamicpdf.pageelements.Label;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Toast;

public class DynamicPDFHelloWorld extends Activity {
    private static String FILE = Environment.getExternalStorageDirectory()
        + "/HelloWorld.pdf";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // Create a document and set it's properties
    Document objDocument = new Document();
    objDocument.setCreator("DynamicPDFHelloWorld.java");
    objDocument.setAuthor("Your Name");
    objDocument.setTitle("Hello World");

    // Create a page to add to the document
    Page objPage = new Page(PageSize.LETTER, PageOrientation.PORTRAIT,
            54.0f);

    // Create a Label to add to the page
    String strText = "Hello World...\nFrom DynamicPDF Generator "
            + "for Java\nDynamicPDF.com";
    Label objLabel = new Label(strText, 0, 0, 504, 100,
            Font.getHelvetica(), 18, TextAlign.CENTER);

    // Add label to page
    objPage.getElements().add(objLabel);

    // Add page to document
    objDocument.getPages().add(objPage);

    try {
        // Outputs the document to file
        objDocument.draw(FILE);
        Toast.makeText(this, "File has been written to :" + FILE,
                Toast.LENGTH_LONG).show();
    } catch (Exception e) {
        Toast.makeText(this,
                "Error, unable to write to file\n" + e.getMessage(),
                Toast.LENGTH_LONG).show();
    }
}
}

答案 1 :(得分:1)

我刚刚意识到这个问题没有得到答复。无论如何,在我发布这个问题后不久,我发现了itextpdf版本5,这就是我从那时起用于所有项目的内容。他们的网站已经更新,他们在文档方面做得很好。以下是其示例页面的link

答案 2 :(得分:1)

您将找到实际正常工作的正确代码。用于创建pdf文件,在其中放入一些内容,保存并打开新创建的文件。

为此,您需要将iTextG的jar添加到您的项目中:

如果您想将布局或视图转换为pdf,则必须从布局中创建图像,然后添加到pdf.Perfect教程中,通过此Link。希望这会帮助你们。谢谢。

简单创建和打开pdf:

//从文本创建pdf文件的方法,保存然后将其打开以显示

public void createandDisplayPdf(String text) {

    Document doc = new Document();

    try {
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/PDF";

        File dir = new File(path);
        if(!dir.exists())
            dir.mkdirs();

        File file = new File(dir, "mypdffile.pdf");
        FileOutputStream fOut = new FileOutputStream(file);

        PdfWriter.getInstance(doc, fOut);

        //open the document
        doc.open();

        Paragraph p1 = new Paragraph(text);
        Font paraFont= new Font(Font.FontFamily.COURIER);
        p1.setAlignment(Paragraph.ALIGN_CENTER);
        p1.setFont(paraFont);

        //add paragraph to document
        doc.add(p1);

    } catch (DocumentException de) {
        Log.e("PDFCreator", "DocumentException:" + de);
    } catch (IOException e) {
        Log.e("PDFCreator", "ioException:" + e);
    }
    finally {
        doc.close();
    }

    viewPdf("mypdffile.pdf", "PDF");
}

// Method for opening a pdf file
private void viewPdf(String file, String directory) {

    File pdfFile = new File(Environment.getExternalStorageDirectory() + "/" + directory + "/" + file);
    Uri path = Uri.fromFile(pdfFile);

    // Setting the intent for pdf reader
    Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
    pdfIntent.setDataAndType(path, "application/pdf");
    pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    try {
        startActivity(pdfIntent);
    } catch (ActivityNotFoundException e) {
        Toast.makeText(this, "Can't read pdf file", Toast.LENGTH_SHORT).show();
    }
}