android - 在 Android 应用程序中创建、写入和显示 PDF 文件

标签 android pdf itext

我有一个 Android 应用程序,它基本上是一种接受用户输入的表单。此输入存储在数据库中。但我想用用户输入的信息创建一个 pdf 文件并显示它,以便用户可以打印文件或将文件保存到他们的 android note 选项卡。最好的方法是什么。我已经看到 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);
    }
}

这是主要 Activity 。

 <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" />

最佳答案

这样做:

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. http://www.dynamicpdf.com/Blog/post/2012/06/15/Generating-PDFs-Dynamically-on-Android.aspx

  2. https://github.com/JoanZapata/android-pdfview

  3. How to create PDFs in an Android app?

  4. Render a PDF file using Java on Android

关于android - 在 Android 应用程序中创建、写入和显示 PDF 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29941864/

相关文章:

c# - 在 C# 中使用 iTextSharp 和 asp 图像调整数据库中的图像大小

android - 如何解决 sdk 17 和 18 之间列表项布局行为变化的变化?

android - nineoldandroids - setDuration 不适用于 AnimatorSet

android - 具有FAB风格的自定义按钮

java - doInBackground 需要很长时间才能启动

php - 如何使用 anchor 标记打开存储在 MySQL 表中的 PDF 文件

java - 如何使用 itext 和 java 读取 pdf 并获取表格单元格高度

powershell - 使用PDFTK将PDF分成多页?

android - PrintedPDFDocument 生成的 PDF 包含具有某种网格布局的灰色框

java - iText 和 HTML 标签