使用itext在android中创建pdf

时间:2015-04-02 08:31:09

标签: java android itext

我在android eclipse中使用itext创建pdf时遇到问题

如果给出了引导程序条目,我无法创建pdf,在我的案例中是Android 5.0.1。如果我删除bootstrap条目,我能够创建pdf但无法启动活动,因为android 5.0.1包含android jar。你能告诉我如何解决这个问题吗? 此外,如果我使它成为非活动类,我希望能够在另一个活动类中创建Non活动类的对象,以便我可以从活动类调用方法。请告诉我如何实现这一目标。

1 个答案:

答案 0 :(得分:0)

从这里http://itextpdf.com/product/itextg下载iText API并将其添加到您的项目中。

使用此类并调用所需的函数来创建pdf

public class CreatePDF {

    private static Font normalFont = new Font(Font.FontFamily.TIMES_ROMAN, 25,
            Font.NORMAL, BaseColor.BLACK);

    private static Font Head = new Font(Font.FontFamily.TIMES_ROMAN, 35,
            Font.BOLD, BaseColor.BLACK);

    //Path is the path where you want your pdf to get stored
    public void createPDFDoc(ArrayList<notesWrapper> notesList,String path) {
        // TODO Auto-generated method stub
        Document document = new Document();
        try {
            PdfWriter.getInstance(document, new FileOutputStream(path));
            document.open();

            for(int i=0;i<notesList.size();i++)
            {               


                addContentHead(document,"Image "+(i+1));                
                addContent(document,notesList.get(i).message);
                if(i<notesList.size())
                {
                    document.newPage();
                }
            }

            document.close();

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
    }

    private void addContent(Document document,String content) throws DocumentException {


        Paragraph preface = new Paragraph();              
        addEmptyLine(preface, 1);

        if(!content.equalsIgnoreCase("insert note"))
        preface.add(new Paragraph(content, normalFont));

        else
            addEmptyLine(new Paragraph(), 1);

        addEmptyLine(preface, 3);
        document.add(preface);



    }


    private void addContentHead(Document document,String content) throws DocumentException {


        Paragraph preface = new Paragraph();              
        addEmptyLine(preface, 1);

        preface.add(new Paragraph(content, Head));
        addEmptyLine(preface, 3);
        document.add(preface);



    }



    private static void addEmptyLine(Paragraph paragraph, int number) {
        for (int i = 0; i < number; i++) {
            paragraph.add(new Paragraph(" "));
        }
    }


}