在Android中创建PDF

时间:2015-02-17 08:11:27

标签: java android

我已参考PDF creation的这篇文章,我想在PDF中打印名字姓氏。在参考文章之后,我在代码中进行了更改并在下面提供了我的代码。

我主要收到这些系统错误。

  1. java.lang.RuntimeException:未找到the.document.is.not.open
  2. 的消息
  3. at com.itextpdf.text.pdf.pdfwriter.getdirectcontent(pdfwriter.java:742)在android中 3.at com.example.pdf.MainActivity.onClick(MainActivity.java:73)
  4. 更改原始代码后,这是我的代码。

            package com.example.pdf;
    
            import java.io.ByteArrayOutputStream;
            import java.io.File;
            import java.io.FileOutputStream;
            import java.io.IOException;
            import java.io.InputStream;
    
            import android.graphics.Bitmap;
            import android.graphics.BitmapFactory;
            import android.os.Bundle;
            import android.os.Environment;
            import android.support.v7.app.ActionBarActivity;
            import android.util.Log;
            import android.view.View;
            import android.view.View.OnClickListener;
            import android.widget.Button;
            import android.widget.EditText;
    
            import com.itextpdf.text.Document;
            import com.itextpdf.text.DocumentException;
            import com.itextpdf.text.PageSize;
            import com.itextpdf.text.Paragraph;
            import com.itextpdf.text.pdf.BaseFont;
            import com.itextpdf.text.pdf.PdfContentByte;
            import com.itextpdf.text.pdf.PdfWriter;
    
            public class MainActivity extends ActionBarActivity implements OnClickListener {
    
                EditText firstName_edt;
                EditText lastName_edt;
                Button preView_btn;
                private BaseFont bfBold;
                private String filepath = "MyInvoices";
                private String filename = "Sample.pdf";
                private File pdfFile;
                private static final String LOG_TAG = "GeneratePDF";
    
                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_main);
    
                    /*InputStream license = this.getResources().openRawResource(R.raw.itextkey);
                      LicenseKey.loadLicenseFile(license);*/
    
                    firstName_edt = (EditText) (findViewById(R.id.activity_main_firstname_edt));
    
                    lastName_edt = (EditText) (findViewById(R.id.activity_main_lastname_edt));
    
                    preView_btn = (Button) (findViewById(R.id.activity_main_preview_btn));
    
                    preView_btn.setOnClickListener(this);
                    if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
                        Log.v(LOG_TAG,
                                "External Storage not available or you don't have permission to write");
                    } else {
                        // path for the PDF file in the external storage
                        pdfFile = new File(getExternalFilesDir(filepath), filename);
                    }
    
                }
    
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
    
                    switch (v.getId()) {
                    case R.id.activity_main_preview_btn:
    
                        String firstaName_str = firstName_edt.getText().toString();
                        String lastName_str = lastName_edt.getText().toString();
                        createPdf(firstaName_str, lastName_str);
    
                        break;
                    default:
                        break;
                    }
                }
    
                private void createPdf(String firstNAME, String lastNAME) {
                    // TODO Auto-generated method stub
    
                    // create file
                    try {
    
                        // create document
                        Document document = new Document(PageSize.A4.rotate(), 50, 50, 50,
                                50);
    
                        PdfWriter docWriter = PdfWriter.getInstance(document,
                                new FileOutputStream(pdfFile));
    
                        PdfContentByte cb = docWriter.getDirectContent();
    
                        document.open();
    
                        // initialize fonts
                        initializeFonts();
    
                        // set logo image
                        InputStream input = getAssets().open("ic_launcher.png");
    
                        Bitmap bitmap = BitmapFactory.decodeStream(input);
    
                        ByteArrayOutputStream stream = new ByteArrayOutputStream();
    
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
    
                        com.itextpdf.text.Image logo = com.itextpdf.text.Image
                                .getInstance(stream.toByteArray());
                        logo.setAbsolutePosition(25, 700);
                        logo.scalePercent(25);
                        document.add(logo);
    
                        // create paragraph
                        document.add(new Paragraph("Personal Details"));
                        document.add(new Paragraph("Name:Sachin Singh"));
                        document.add(new Paragraph("Address: Kolkata"));
                        document.add(new Paragraph("email: ash@gmail.com"));
                        document.add(new Paragraph("Gender:F"));
    
                        // set firstname and lastname from edittext
                        createHeadings(cb, 450, 135, firstNAME, lastNAME);
    
                    } catch (Exception e) {
                        // TODO: handle exception
                        e.printStackTrace();
                    }
    
                }
    
                private static boolean isExternalStorageReadOnly() {
                    String extStorageState = Environment.getExternalStorageState();
                    if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
                        return true;
                    }
                    return false;
                }
    
                private static boolean isExternalStorageAvailable() {
                    String extStorageState = Environment.getExternalStorageState();
                    if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
                        return true;
                    }
                    return false;
                }
    
                private void initializeFonts() {
                    // TODO Auto-generated method stub
                    try {
                        bfBold = BaseFont.createFont(BaseFont.HELVETICA_BOLD,
                                BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    
                    } catch (DocumentException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
    
                // method for setting firstname and last name
                private void createHeadings(PdfContentByte cb, float x, float y,
                        String firstNAME, String lastNAME) {
                    // TODO Auto-generated method stub
                    cb.beginText();
                    cb.setFontAndSize(bfBold, 8);
                    cb.setTextMatrix(x, y);
                    cb.showText(firstNAME.trim());
                    cb.showText(lastNAME.trim());
                    cb.endText();
                }
            }
    

    Xml文件

      <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical" >
    
            <EditText
                android:id="@+id/activity_main_firstname_edt"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="enter first name"
                android:ems="10" >
    
                <requestFocus />
            </EditText>
    
            <EditText
                android:id="@+id/activity_main_lastname_edt"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                 android:hint="enter last name"
                android:ems="10" />
    
            <Button
                android:id="@+id/activity_main_preview_btn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Preview" />
    
        </LinearLayout>
    
     logcat data
    
    02-18 00:38:10.789: I/eFrame(32423): pkgname_before:com.example.pdf  class:com.android.launcher2.Launcher
    02-18 00:39:45.171: I/eFrame(32423): pkgname_before:com.sec.android.app.launcher  class:com.example.pdf.MainActivity
    02-18 00:39:53.159: W/System.err(32410): com.itextpdf.text.DocumentException: No message found for 1.not.found.as.resource
    02-18 00:39:53.159: W/System.err(32410):    at com.itextpdf.text.pdf.Type1Font.<init>(Type1Font.java:192)
    02-18 00:39:53.159: W/System.err(32410):    at com.itextpdf.text.pdf.BaseFont.createFont(BaseFont.java:699)
    02-18 00:39:53.159: W/System.err(32410):    at com.itextpdf.text.pdf.BaseFont.createFont(BaseFont.java:622)
    02-18 00:39:53.159: W/System.err(32410):    at com.itextpdf.text.pdf.BaseFont.createFont(BaseFont.java:457)
    02-18 00:39:53.159: W/System.err(32410):    at com.example.pdf.MainActivity.initializeFonts(MainActivity.java:162)
    02-18 00:39:53.159: W/System.err(32410):    at com.example.pdf.MainActivity.createPdf(MainActivity.java:101)
    02-18 00:39:53.159: W/System.err(32410):    at com.example.pdf.MainActivity.onClick(MainActivity.java:74)
    02-18 00:39:53.169: W/System.err(32410):    at com.itextpdf.text.pdf.PdfWriter.addSimple(PdfWriter.java:2280)
    02-18 00:39:53.169: W/System.err(32410):    at com.itextpdf.text.pdf.PdfContentByte.setFontAndSize(PdfContentByte.java:1704)
    02-18 00:39:53.169: W/System.err(32410):    at com.example.pdf.MainActivity.createHeadings(MainActivity.java:137)
    02-18 00:39:53.169: W/System.err(32410):    at com.example.pdf.MainActivity.createPdf(MainActivity.java:119)
    02-18 00:39:53.169: W/System.err(32410):    at com.example.pdf.MainActivity.onClick(MainActivity.java:74)
    

1 个答案:

答案 0 :(得分:0)

在调用方法之前调用方法&#34; document.open()&#34; docWriter.getDirectContent()&#34;:

document.open();

PdfContentByte cb = docWriter.getDirectContent();

关于您的字体例外,我不使用BaseFont。请试试这个:

// colors
    private static final BaseColor colorFont = new BaseColor(51, 51, 51);
    private static final BaseColor colorBlue = new BaseColor(32, 119, 215);

        // fonts
        private static final Font fontDefault = new Font(FontFamily.HELVETICA, 10,
                Font.NORMAL, colorFont);
        private static final Font fontBold = new Font(FontFamily.HELVETICA, 10,
                Font.BOLD, colorFont);
        private static final Font fontTitle = new Font(FontFamily.HELVETICA, 10,
                Font.BOLD, colorBlue);

    new Paragraph(new Chunk("Personal Details",
                        fontDefault))