10

AndroidでiTextまたは他のライブラリを使用してPDFファイルを作成するには?

Android用のiTextに関するチュートリアルはありますか?

ありがとう

4

6 に答える 6

14

iText を使用して PDF を作成できます。最新バージョン (5.1.3) を使用し、ビルド パスに itextpdf-5.1.3.jar のみを含めます。このようなものを使用して、pdf の作成を実行できます。

Document document = new Document();
file = Environment.getExternalStorageDirectory().getPath() + "/Hello.pdf"
PdfWriter.getInstance(document,new FileOutputStream(file));
document.open();
Paragraph p = new Paragraph("Hello PDF");
document.add(p);
document.close();

また、manifest.xml で外部ストレージへの書き込み権限を使用することを忘れないでください。

于 2012-01-21T18:20:07.490 に答える
12

それは簡単です、例えば

ここに私のリポジトリのコード(更新されたリンク)

gradle.build

compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.madgag:scpkix-jdk15on:1.47.0.1'
compile 'com.itextpdf:itextpdf:5.0.6'

activity_main.xml

 <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.hackro.itext.MainActivity">
    
    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btnwrite"
        android:text="PDF"
        android:onClick="GeneratePDF"
        />
    </RelativeLayout>

MainActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.itextpdf.text.pdf.BaseFont;
import java.io.File;

public class MainActivity extends Activity {

    private static final String LOG_TAG = "GeneratePDF";


    private BaseFont bfBold;

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



    }


    public void GeneratePDF(View view)
    {
        // TODO Auto-generated method stub
        String filename = "david";
        String filecontent = "Contenido";
        Metodos fop = new Metodos();
        if (fop.write(filename, filecontent)) {
            Toast.makeText(getApplicationContext(),
                    filename + ".pdf created", Toast.LENGTH_SHORT)
                    .show();
        } else {
            Toast.makeText(getApplicationContext(), "I/O error",
                    Toast.LENGTH_SHORT).show();
        }
    }

  }

Metodos.java

 import android.util.Log;
    
    import com.itextpdf.text.BaseColor;
    import com.itextpdf.text.Document;
    import com.itextpdf.text.DocumentException;
    import com.itextpdf.text.Element;
    import com.itextpdf.text.Font;
    import com.itextpdf.text.Paragraph;
    import com.itextpdf.text.Phrase;
    import com.itextpdf.text.pdf.PdfPCell;
    import com.itextpdf.text.pdf.PdfPTable;
    import com.itextpdf.text.pdf.PdfWriter;
    
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    /**
     * Created by hackro on 24/11/15.
     */
    public class Metodos {
    
    
        public Boolean write(String fname, String fcontent) {
            try {
                String fpath = "/sdcard/" + fname + ".pdf";
                File file = new File(fpath);
    
                if (!file.exists()) {
                    file.createNewFile();
                }
    
                Font bfBold12 = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD, new BaseColor(0, 0, 0));
                Font bf12 = new Font(Font.FontFamily.TIMES_ROMAN, 12);
    
    
                Document document = new Document();
    
                PdfWriter.getInstance(document,
                        new FileOutputStream(file.getAbsoluteFile()));
                document.open();
    
                document.add(new Paragraph("Sigueme en Twitter!"));
    
                document.add(new Paragraph("@DavidHackro"));
                document.close();
    
                return true;
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            } catch (DocumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return false;
            }
        }}
    

結果

幸運を

于 2015-11-24T13:32:16.870 に答える
3

これは、Itext ライブラリを使用してテキストと画像のコンテンツを含む pdf ファイルを作成し、pdf ファイルを外部ストレージの場所に保存するための私のサンプル コーディングです。唯一のことは、itext ライブラリをダウンロードしてプロジェクトに追加する必要があることです。

private void createPdf() {
                // TODO Auto-generated method stub
                com.itextpdf.text.Document document = new com.itextpdf.text.Document();

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

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

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


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

                        PdfWriter.getInstance(document, fOut);

                        //open the document
                        document.open();


                        Paragraph p1 = new Paragraph("Sample PDF CREATION USING IText");
                        Font paraFont= new Font(Font.FontFamily.COURIER);
                        p1.setAlignment(Paragraph.ALIGN_CENTER);
                        p1.setFont(paraFont);

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

                         Paragraph p2 = new Paragraph("This is an example of a simple paragraph");
                         Font paraFont2= new Font(Font.FontFamily.COURIER,14.0f,0, CMYKColor.GREEN);
                         p2.setAlignment(Paragraph.ALIGN_CENTER);
                         p2.setFont(paraFont2);

                         document.add(p2);

                         ByteArrayOutputStream stream = new ByteArrayOutputStream();
                         Bitmap bitmap = BitmapFactory.decodeResource(getBaseContext().getResources(), R.drawable.ic_launcher);
                         bitmap.compress(Bitmap.CompressFormat.JPEG, 100 , stream);
                         Image myImg = Image.getInstance(stream.toByteArray());
                         myImg.setAlignment(Image.MIDDLE);

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




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

            }      
于 2013-09-17T07:39:14.560 に答える
1

itextpdf/itext7 ライブラリを使用して、データから pdf ファイルを作成するためのサンプル プロジェクトを作成しました。

プロジェクト リンクの例: https://github.com/rheyansh/RPdfGenerator

アプリケーション gradle に以下の依存関係を追加します。

implementation 'com.itextpdf:itext7-core:7.1.12'

重要事項

AndroidManifest.xml に WRITE_EXTERNAL_STORAGE 権限を追加

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

AndroidManifest.xml にファイル プロバイダーを追加する

<provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="com.rheyansh.rpdfgenerator.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths" />
    </provider>

XML リソース フォルダーを追加します (サンプル フォルダーの provider_paths.xml を参照)。

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path name="external_files" path="."/>
</paths>

RPdfGenerator クラスを作成する

import android.content.Context
import android.os.Environment
import com.rheyansh.model.RTransaction
import android.widget.Toast
import com.itextpdf.io.font.constants.StandardFonts
import com.itextpdf.kernel.colors.ColorConstants
import com.itextpdf.kernel.font.PdfFontFactory
import com.itextpdf.kernel.pdf.PdfDocument
import com.itextpdf.kernel.pdf.PdfWriter
import com.itextpdf.kernel.pdf.action.PdfAction
import com.itextpdf.layout.Document
import com.itextpdf.layout.element.Paragraph
import com.itextpdf.layout.element.Table
import com.itextpdf.layout.element.Text
import com.itextpdf.layout.property.TextAlignment
import com.itextpdf.layout.property.UnitValue
import com.rheyansh.lenden.model.RPdfGeneratorModel
import java.io.File
import java.io.FileOutputStream

object RPdfGenerator {

    private val linkSample = "https://github.com/rheyansh/RPdfGenerator"

    fun generatePdf(context: Context, info: RPdfGeneratorModel) {

        val FILENAME = info.header + ".pdf"
        val filePath = getAppPath(context) + FILENAME

        if (File(filePath).exists()) {
            File(filePath).delete()
        }

        val fOut = FileOutputStream(filePath)
        val pdfWriter = PdfWriter(fOut)

        // Creating a PdfDocument
        val pdfDocument =
            PdfDocument(pdfWriter)
        val layoutDocument = Document(pdfDocument)

        // title
        addTitle(layoutDocument, info.header)

        //add empty line
        addEmptyLine(layoutDocument,1)

        //Add sub heading
        val appName = "RPdfGenerator"
        addSubHeading(layoutDocument, "Generated via: ${appName}")
        addLink(layoutDocument, linkSample)

        //add empty line
        addEmptyLine(layoutDocument,1)

        // customer reference information
        addDebitCredit(layoutDocument, info)

        //add empty line
        addEmptyLine(layoutDocument,1)

        //Add sub heading
        addSubHeading(layoutDocument, "Transactions")

        //Add list
        addTable(layoutDocument, info.list)

        layoutDocument.close()
        Toast.makeText(context, "Pdf saved successfully to location $filePath", Toast.LENGTH_LONG).show()

        //FileUtils.openFile(context, File(filePath))
    }

    private fun getAppPath(context: Context): String {
        val dir = File(
            Environment.getExternalStorageDirectory()
                .toString() + File.separator
                    + context.resources.getString(R.string.app_name)
                    + File.separator
        )
        if (!dir.exists()) {
            dir.mkdir()
        }
        return dir.path + File.separator
    }

    private fun addTable(layoutDocument: Document, items: List<RTransaction>) {

        val table = Table(
            UnitValue.createPointArray(
                floatArrayOf(
                    100f,
                    180f,
                    80f,
                    80f,
                    80f,
                    100f
                )
            )
        )

        // headers
        //table.addCell(Paragraph("S.N.O.").setBold())
        table.addCell(Paragraph("Item").setBold())
        table.addCell(Paragraph("Customer").setBold())
        table.addCell(Paragraph("Qty").setBold())
        table.addCell(Paragraph("Price/Q").setBold())
        table.addCell(Paragraph("Total").setBold())
        table.addCell(Paragraph("Date").setBold())

        // items
        for (a in items) {
//            table.addCell(Paragraph(a.SNO.toString() + ""))
            table.addCell(Paragraph(a.itemName + ""))
            table.addCell(Paragraph(a.custName + ""))
            table.addCell(Paragraph(a.quantity.toString() + ""))
            table.addCell(Paragraph(a.pricePerUnit.toString() + ""))
            table.addCell(Paragraph((a.quantity * a.pricePerUnit).toString() + ""))
            table.addCell(Paragraph(a.transactionDateStr + ""))
        }
        layoutDocument.add(table)
    }

    private fun addEmptyLine(layoutDocument: Document, number: Int) {
        for (i in 0 until number) {
            layoutDocument.add(Paragraph(" "))
        }
    }

    private fun addDebitCredit(layoutDocument: Document, info: RPdfGeneratorModel) {

        val table = Table(
            UnitValue.createPointArray(
                floatArrayOf(
                    100f,
                    160f
                )
            )
        )

        table.addCell(Paragraph("Total Credit").setBold())
        table.addCell(Paragraph(info.totalCredit + ""))
        table.addCell(Paragraph("Total Debit").setBold())
        table.addCell(Paragraph(info.totalDebit + ""))
        table.addCell(Paragraph("Total Profit").setBold())
        table.addCell(Paragraph(info.totalProfit + ""))

        layoutDocument.add(table)
    }

    private fun addSubHeading(layoutDocument: Document, text: String) {
        layoutDocument.add(
            Paragraph(text).setBold()
                .setTextAlignment(TextAlignment.CENTER)
        )
    }

    private fun addLink(layoutDocument: Document, text: String) {

        val blueText: Text = Text(text)
            .setFontColor(ColorConstants.BLUE)
            .setFont(PdfFontFactory.createFont(StandardFonts.HELVETICA_BOLD))

        layoutDocument.add(
            Paragraph(blueText)
                .setAction(PdfAction.createURI(text))
                .setTextAlignment(TextAlignment.CENTER)
                .setUnderline()
                .setItalic()
        )
    }

    private fun addTitle(layoutDocument: Document, text: String) {
        layoutDocument.add(
            Paragraph(text).setBold().setUnderline()
                .setTextAlignment(TextAlignment.CENTER)
        )
    }
}

RPdfGeneratorModel

class RPdfGeneratorModel(list: List<RTransaction>, header: String) {

    var list = emptyList<RTransaction>()
    var header = ""
    var totalCredit = ""
    var totalDebit = ""
    var totalProfit = ""

    init {
        this.list = list
        this.header = header
        calculateTotal(list)
    }

    private fun calculateTotal(items: List<RTransaction>) {
        val totalPlus = items.map {
            if (it.transType == RTransactionType.plus) {
                it.totalPrice
            } else { 0.0 }
        }.sum()

        val totalMinus = items.map {
            if (it.transType == RTransactionType.minus) {
                it.totalPrice
            } else { 0.0 }
        }.sum()

        val final = totalPlus - totalMinus
        totalDebit = "-" + totalMinus.toString()
        totalCredit = totalPlus.toString()
        totalProfit = final.toString()
    }
}

RTransaction モデル

enum class RTransactionType { plus, minus }

class RTransaction {

    var itemName: String = ""
    var custName: String = ""
    var transType: RTransactionType = RTransactionType.plus
    var pricePerUnit: Double = 0.0
    var quantity: Int = 0
    var totalPrice: Double = 0.0
    var transactionDateStr: String = ""

    constructor() {
    }
}

ダミーデータを作成するために、アクティビティクラスに以下の関数を記述します

private fun dummyModel(): RPdfGeneratorModel {
        val list = dummyTransactions()
        val header = "Statement"
        val dummy = RPdfGeneratorModel(list, header)
        return dummy
    }

    private fun dummyTransactions(): List<RTransaction> {

        val list = arrayListOf<RTransaction>()

        val i1 = RTransaction()
        i1.custName = "Johan Store"
        i1.itemName = "Snacks"
        i1.quantity = 4
        i1.pricePerUnit = 40.0
        i1.totalPrice = i1.quantity * i1.pricePerUnit
        i1.transactionDateStr = "10 Sep, 20"
        i1.transType = RTransactionType.plus
        list.add(i1)


        val i2 = RTransaction()
        i2.custName = "Alice Store"
        i2.itemName = "Chocolate"
        i2.quantity = 3
        i2.pricePerUnit = 79.0
        i2.totalPrice = i2.quantity * i2.pricePerUnit
        i2.transactionDateStr = "9 Sep, 20"
        i2.transType = RTransactionType.plus
        list.add(i2)

        val i3 = RTransaction()
        i3.custName = "Alexa Mall"
        i3.itemName = "Shoes"
        i3.quantity = 2
        i3.pricePerUnit = 177.0
        i3.totalPrice = i3.quantity * i3.pricePerUnit
        i3.transactionDateStr = "9 Sep, 20"
        i3.transType = RTransactionType.minus
        list.add(i3)

        val i4 = RTransaction()
        i4.custName = "Zainab Baba"
        i4.itemName = "Chips"
        i4.quantity = 5
        i4.pricePerUnit = 140.0
        i4.totalPrice = i4.quantity * i4.pricePerUnit
        i4.transactionDateStr = "8 Sep, 20"
        i4.transType = RTransactionType.plus
        list.add(i4)

        list.add(i1)
        list.add(i2)
        list.add(i3)
        list.add(i4)

        list.add(i1)
        list.add(i2)
        list.add(i3)
        list.add(i4)


        return list
    }

ここで RPdfGenerator 関数を呼び出します。呼び出す前に、必ず WRITE_EXTERNAL_STORAGE パーミッションを要求してください。詳細については、サンプルプロジェクトをチェックしてください

val dummyInfo = dummyModel()
                RPdfGenerator.generatePdf(this, dummyInfo)
于 2020-09-10T13:20:29.250 に答える
0

私は Java Swing アプリケーションで iText を使用しました。いくつかの基本的な PDF ファイルを作成するのにうまく機能しました。コードは次のようになります。

    @Override public void buildPDF(List<Folder> folders) {        
    Document document = new Document();
    String fname = "";
    boolean open = false;
    try {
            // step 2:
            // we create a writer that listens to the document
            // and directs a PDF-stream to a file
            fname = filename(getName()) + "-" + filename(getDataset().getName()) + ".pdf";

            PdfWriter writer = PdfWriter.getInstance(document,
                            new FileOutputStream(fname));

            for (int i = 0; i < folders.size(); i++ ) {
                // grab the folder
                LIFolder f = (LIFolder) folders.get(i);

                if (f == null) continue;

                open = true;
                break;
            }

            // we have no valid folders
            if (folders.size() > 0 && !open) {
                // they selected an empty row
                javax.swing.JOptionPane.showMessageDialog(null, BUNDLE.getString("report-none-selected"), 
                        BUNDLE.getString("report-none-selected-title"), 
                        javax.swing.JOptionPane.ERROR_MESSAGE);
                return;
            }

            if (folders.size() == 0) {
                // get all folders from dataset
                folders = FolderFinder.findAll(getSession(), getDataset());
            }

            open = false;
            for (int i = 0; i < folders.size(); i++ ) {
                // grab the folder
                LIFolder f = (LIFolder) folders.get(i);

                if (f == null) continue;

                if (!open) {
                    open = true;
                    document.open();
                }

                Paragraph p = new Paragraph(BUNDLE.getString("report-heading-summary-main"), getPageHeadingFont());
                p.setAlignment("center");
                document.add(p);
                p = new Paragraph(BUNDLE.getString("report-heading-summary-main-sub"), this.pageHeadingFont1);
                p.setAlignment("center");
                document.add(p);

                blankLine(document);
                drawLine(writer);

                ///////////////////////////////////////////////////////////////////////////////////////////////////
                // Primary Statement Details
                ///////////////////////////////////////////////////////////////////////////////////////////////////                    
                p = new Paragraph("Primary Statement Details", this.pageHeadingFont2);
                p.setAlignment("center");
                document.add(p);

                blankLine(document);
                PdfPTable table = new PdfPTable(4);

                table.addCell(new BorderlessCell(new Paragraph("Dataset:", getFieldHeadingFont())));
                BorderlessCell cell = new BorderlessCell(new Paragraph(getDataset().getName(), getTextFont()));
                cell.setColspan(3);
                table.addCell(cell);

                table.addCell(new BorderlessCell(new Paragraph("Data Entry Clerk:", getFieldHeadingFont())));
                cell = new BorderlessCell(new Paragraph(
                        (f.getDataEntryClerk() != null ? f.getDataEntryClerk().toDescriptionPathString() : emptyIfNull(null)), 
                        getTextFont()));
                cell.setColspan(3);
                table.addCell(cell);

                table.setWidthPercentage(100);
                cell = new BorderlessCell(new Paragraph("Statement Number:", getFieldHeadingFont()));
                table.addCell(cell);
                table.addCell(new BorderlessCell(new Paragraph(f.getReferenceId(), getTextFont())));

                table.addCell(new BorderlessCell(new Paragraph("Statement Date:", getFieldHeadingFont())));

                String strDate = "";
                java.util.Date date = f.getStatementDate();
                if (date != null) {
                    SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy"); 
                    strDate = formatter.format(date);
                }
                table.addCell(new BorderlessCell(new Paragraph(strDate, getTextFont())));

                table.addCell(new BorderlessCell(new Paragraph("Statement Location:", getFieldHeadingFont())));
                cell = new BorderlessCell(new Paragraph(emptyIfNull(f.getTakerLocation()), getTextFont()));
                cell.setColspan(3);
                table.addCell(cell);

                table.addCell(new BorderlessCell(new Paragraph("Statement keywords:", getFieldHeadingFont())));
                cell = new BorderlessCell(new Paragraph(emptyIfNull(f.getKeywords()), getTextFont()));
                cell.setColspan(3);
                table.addCell(cell);

                document.add(table);
                ///////////////////////////////////////////////////////////////////////////////////////////////////


                ///////////////////////////////////////////////////////////////////////////////////////////////////
                // Statement Giver's Details
                ///////////////////////////////////////////////////////////////////////////////////////////////////                    
                LIPerson p01 = null;
                Set<Actor> actors = f.getActors();
                Iterator iter = actors.iterator();
                while (iter.hasNext()) {
                    Actor actor = (Actor) iter.next();
                    if (actor instanceof LIPerson) {
                        LIPerson person = (LIPerson) actor;
                        if (person.getReferenceId().toString().equalsIgnoreCase("p01") ) {
                            p01 = person;
                            break;
                        }
                    }
                }

                blankLine(document);
                drawLine(writer);
                p = new Paragraph(new Chunk("Statement Giver's Details", this.pageHeadingFont2));
                p.setAlignment("center");                        
                document.add(p);

                java.util.ArrayList giver = new java.util.ArrayList();
                if (p01 != null)
                    giver.add(p01);

                table = new PdfPTable(2);
                table.setWidthPercentage(100f);
                table.addCell(new BorderlessCell(new Paragraph("Name of Statement Giver:", getFieldHeadingFont())));
                table.addCell(new BorderlessCell(new Paragraph(ActorsToString(giver), getTextFont())));

                table.addCell(new BorderlessCell(new Paragraph("Sex:", getFieldHeadingFont())));
                if (p01 == null)
                    table.addCell(new BorderlessCell(new Paragraph(emptyIfNull("TBD"), getTextFont())));
                else
                    table.addCell(new BorderlessCell(new Paragraph((p01.getSex() != null ? p01.getSex().toString() : ""), getTextFont())));

                table.addCell(new BorderlessCell(new Paragraph("Tribe:", getFieldHeadingFont())));
                if (p01 == null)
                    table.addCell(new BorderlessCell(new Paragraph(emptyIfNull(null), getTextFont())));
                else
                    table.addCell(new BorderlessCell(
                            new Paragraph((p01.getEthnicityOrTribe() != null ? p01.getEthnicityOrTribe().toDescriptionPathString() : emptyIfNull(null)), 
                            getTextFont())));

                table.addCell(new BorderlessCell(new Paragraph("Nationality:", getFieldHeadingFont())));
                if (p01 == null)
                    table.addCell(new BorderlessCell(new Paragraph(emptyIfNull(null), getTextFont())));
                else
                    table.addCell(new BorderlessCell(
                            new Paragraph((p01.getNationality() != null ? p01.getNationality().toDescriptionPathString() : emptyIfNull(null)), 
                            getTextFont())));

                table.addCell(new BorderlessCell(new Paragraph("Marital Status:", getFieldHeadingFont())));
                table.addCell(new BorderlessCell(new Paragraph(emptyIfNull(f.getMaritalStatus()), getTextFont())));

                table.addCell(new BorderlessCell(new Paragraph("Education Level:", getFieldHeadingFont())));
                table.addCell(new BorderlessCell(new Paragraph(emptyIfNull(f.getEducationLevel()), getTextFont())));

                table.addCell(new BorderlessCell(new Paragraph("County of Origin:", getFieldHeadingFont())));
                table.addCell(new BorderlessCell(new Paragraph(emptyIfNull(f.getCountyOfOrigin()), getTextFont())));

                table.addCell(new BorderlessCell(new Paragraph("Mother's Name:", getFieldHeadingFont())));
                table.addCell(new BorderlessCell(new Paragraph(emptyIfNull(f.getMothersName()), getTextFont())));

                table.addCell(new BorderlessCell(new Paragraph("Father's Name:", getFieldHeadingFont())));
                table.addCell(new BorderlessCell(new Paragraph(emptyIfNull(f.getFathersName()), getTextFont())));

                table.addCell(new BorderlessCell(new Paragraph("# of Dependents:", getFieldHeadingFont())));
                table.addCell(new BorderlessCell(new Paragraph(Integer.toString(f.getNumDependents()), getTextFont())));

                table.addCell(new BorderlessCell(new Paragraph("Phone Number:", getFieldHeadingFont())));
                table.addCell(new BorderlessCell(new Paragraph(emptyIfNull(f.getPhoneNumber()), getTextFont())));

                document.add(table);

                ///////////////////////////////////////////////////////////////////////////////////////////////////
                // Summary
                ///////////////////////////////////////////////////////////////////////////////////////////////////                    
                blankLine(document);
                drawLine(writer);
                p = new Paragraph(new Chunk("Summary", this.pageHeadingFont2));
                p.setAlignment("center");                        
                document.add(p);
                p = new Paragraph(new Chunk(emptyIfNull(f.getSourceSummary()), getTextFont()));
                document.add(p);

                ///////////////////////////////////////////////////////////////////////////////////////////////////
                // Incident(s)
                ///////////////////////////////////////////////////////////////////////////////////////////////////                                        
                Set<Act> acts = f.getActs();

                if (acts.size() > 0) {
                    // sort them by id
                    Hashtable map = new Hashtable();
                    Iterator it = acts.iterator();
                    String[] ids = new String[acts.size()];
                    int x = 0;
                    while (it.hasNext()) {
                        LIAct act = (LIAct) it.next();
                        String index = Integer.toString(act.getId());
                        map.put(index, act);

                        ids[x++] = index;
                    }
                    java.util.Arrays.sort(ids);

                    blankLine(document);
                    drawLine(writer);
                    p = new Paragraph(new Chunk("Act(s)", this.pageHeadingFont2));
                    p.setAlignment("center");                        
                    document.add(p);

                    blankLine(document);
                    table = new PdfPTable(4);
                    table.setWidthPercentage(100);

                    for (int y = 0; y < ids.length; y++) {
                        LIAct act = (LIAct) map.get(ids[y]);

                        table.addCell(new BorderlessCell(new Paragraph("Act ID:", getFieldHeadingFont())));
                        cell = new BorderlessCell(new Paragraph(act.getReferenceId(), getTextFont()));
                        cell.setColspan(3);
                        table.addCell(cell);

                        table.addCell(new BorderlessCell(new Paragraph("Start Date:", getFieldHeadingFont())));
                        table.addCell(new BorderlessCell(new Paragraph((act.getWhen() != null ? act.getWhen().toString():""), getTextFont())));

                        table.addCell(new BorderlessCell(new Paragraph("End Date:", getFieldHeadingFont())));
                        table.addCell(new BorderlessCell(new Paragraph((act.getUntil() != null?act.getUntil().toString():""), getTextFont())));

                        table.addCell(new BorderlessCell(new Paragraph("Location of act:", getFieldHeadingFont())));                            
                        p = new Paragraph(emptyIfNull(act.getWhere().toString()), getTextFont());
                        p.setAlignment(Paragraph.ALIGN_LEFT);
                        cell = new BorderlessCell(p);
                        cell.setColspan(3);                            
                        table.addCell(cell);

                        table.addCell(new BorderlessCell(new Paragraph("Precise Location:", getFieldHeadingFont())));                            
                        p = new Paragraph(emptyIfNull(act.getPreciseLocation()), getTextFont());
                        p.setAlignment(Paragraph.ALIGN_LEFT);
                        cell = new BorderlessCell(p);
                        cell.setColspan(3);                            
                        table.addCell(cell);

                        table.addCell(new BorderlessCell(new Paragraph("Violation:", getFieldHeadingFont())));                            
                        p = new Paragraph(emptyIfNull(act.getViolation().toDescriptionPathString()), getTextFont());
                        p.setAlignment(Paragraph.ALIGN_LEFT);
                        cell = new BorderlessCell(p);
                        cell.setColspan(3);                            
                        table.addCell(cell);

                        table.addCell(new BorderlessCell(new Paragraph("Description:", getFieldHeadingFont())));                                         
                        p = new Paragraph(emptyIfNull(act.getDescriptionLocation()), getTextFont());
                        p.setAlignment(Paragraph.ALIGN_LEFT);
                        cell = new BorderlessCell(p);
                        cell.setColspan(3);                            
                        table.addCell(cell);

                        // add empty cell
                        cell = new BorderlessCell(new Paragraph(""));
                        cell.setColspan(4);
                        table.addCell(cell);                            
                        cell = new BorderlessCell(new Paragraph(""));
                        cell.setColspan(4);
                        table.addCell(cell);                            
                    }

                    document.add(table);
                }                    

                /////////////////////////////////////////////////////////////////////////////////////////////////
                // Victims
                /////////////////////////////////////////////////////////////////////////////////////////////////
                List<Actor> victims = this.getAllVictims(f);

                if (!victims.isEmpty()) {
                    blankLine(document);
                    drawLine(writer);
                    String strVictims = ActorsToString(victims);
                    p = new Paragraph(new Chunk("Victim(s)", this.pageHeadingFont2));
                    p.setAlignment("center");                        
                    document.add(p);

                    p = new Paragraph(new Chunk("Name(s) of Victim(s): ", getFieldHeadingFont()));
                    p.add(new Chunk(strVictims, getTextFont()));
                    document.add(p);

                    String gender = ActorsToGender(victims);
                    p = new Paragraph(new Chunk("Gender: ", getFieldHeadingFont()));
                    p.add(new Chunk(gender, getTextFont()));
                    document.add(p);
                }

                /////////////////////////////////////////////////////////////////////////////////////////////////

                /////////////////////////////////////////////////////////////////////////////////////////////////
                // Perps
                /////////////////////////////////////////////////////////////////////////////////////////////////
                List<Actor> perps = this.getAllPerpetrators(f);
                if (!perps.isEmpty()) {
                    blankLine(document);
                    drawLine(writer);
                    p = new Paragraph(new Chunk("Perpetrator(s)", this.pageHeadingFont2));
                    p.setAlignment("center");                        
                    document.add(p);

                    String strPerps = ActorsToString(perps);
                    p = new Paragraph(new Chunk("Name(s) of alleged perpetrator(s): ", getFieldHeadingFont()));
                    p.add(new Chunk(strPerps, getTextFont()));
                    document.add(p);
                }
                /////////////////////////////////////////////////////////////////////////////////////////////////

                document.newPage();
            }

    } catch (DocumentException de) {
            System.err.println(de.getMessage());
    } catch (java.io.IOException ioe) {
            System.err.println(ioe.getMessage());
    }

    // step 5: we close the document
    if (open) {
        document.close();

        if (!fname.equals("")) {
            // launch it
            Reports.LaunchPDF(fname);        
        }
    }        

}

さらに情報が必要な場合は、お知らせください。幸運を!

于 2011-12-08T18:11:15.147 に答える
0
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();
        }
    }
}

リンクからダウンロードできるlibsファイルにDynamicPDFを追加します

于 2015-03-03T10:57:49.887 に答える