Android根据pdf模板生成pdf文件

我们需要生成一些固定格式的pdf文件或者一些报表数据,那么我们可以用 iText包去做。

需要包含的jar包:iText-5.0.6.jar    iTextAsian.jar ,怎样jar包导入工程,在这里就不再赘述了,可自行网上搜索。

1、在word里建立一个表单,也就是你的pdf模板格式

 

 

2、把word保存为pdf格式

 

 

3、用迅捷pdf编辑器打开保存的pdf

 

 

 

 

 

 

 

 

 

 

 

 

 保存pdf为模板,取名名字“PdfTemplate”(随便取名)。

以下是代码部分:

public void FillPdfTemplate(String id) {
        android.icu.text.SimpleDateFormat simpleDateFormat =
                new android.icu.text.SimpleDateFormat("HHmmss");// HH:mm:ss
        //设置默认时区
        simpleDateFormat.setTimeZone(android.icu.util.TimeZone.getTimeZone("GMT+8:00"));
        //获取当前时间
        Date date2 = new Date(System.currentTimeMillis());
        String sim2 = simpleDateFormat.format(date2);

        String folderName_WaterImage = "WaterImage";
        String folderName_WaterDB = "WaterDB";
        String folderName_WaterPdf = "WaterPdf";

        File sdCardDir_PdfTemplate = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DOWNLOADS), folderName_WaterDB);
        File sdCardDir_WaterPdf = new File(Environment.getExternalStorageDirectory(),
                folderName_WaterPdf);

        //模板路径
        String templatePath = sdCardDir_PdfTemplate + "/" + "WaterTemplate.pdf";
        //生成的新文件路径
        String newPDFPath = sdCardDir_WaterPdf + "/" +
                mWaterInfo.SamplingDate + "_" + mWaterInfo.WellNumber + "_" + sim2 + ".pdf";

/**
 * 使用中文字体
 * 如果是利用 AcroFields填充值的不需要在程序中设置字体,在模板文件中设置字体为中文字体就行了
 */
        BaseFont bf = null;
        try {
            bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Font FontChinese = new Font(bf, 12, Font.NORMAL);

        PdfReader reader;
        FileOutputStream out;
        ByteArrayOutputStream bos;
        PdfStamper stamper;
        try {
            out = new FileOutputStream(newPDFPath);//输出流
            reader = new PdfReader(templatePath);//读取pdf模板
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();

            String[] strDate = mWaterInfo.SamplingDate.split("-");
            String[] str = {
                    mWaterInfo.WellNumber, mWaterInfo.Longitude + "," + mWaterInfo.Latitude,
                    strDate[0], strDate[1], strDate[2], mWaterInfo.SamplingTime,
                    mWaterInfo.SampleMethods, mWaterInfo.SampleDepth, mWaterInfo.Temperature,
                    mWaterInfo.Weather, mWaterInfo.WaterLevel, mWaterInfo.WaterTemp1,
                    mWaterInfo.ORP1, mWaterInfo.DO1, mWaterInfo.pH1, mWaterInfo.CT1, mWaterInfo.NTU1,
                    mWaterInfo.Smell, mWaterInfo.Thing, mWaterInfo.Color, mWaterInfo.SamplingName,
                    mWaterInfo.RecordingName};

            String[] it = new String[]{
                    "Text1", "Text2", "Text3", "Text4", "Text5", "Text6", "Text7",
                    "Text8", "Text9", "Text10", "Text11", "Text12", "Text13", "Text14", "Text15",
                    "Text16", "Text17", "Text18", "Text19", "Text20", "Text21", "Text22",};

            for (int i = 0; i < 22; i++) {
                form.setFieldProperty(it[i], "textfont", bf, null);
                form.setField(it[i], str[i]);
            }


            stamper.setFormFlattening(true);//如果为false那么生成的PDF文件还能编辑,一定要设为true
            stamper.close();

            Document doc = new Document();

            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();
            PdfImportedPage importPage = copy.getImportedPage(
                    new PdfReader(bos.toByteArray()), 1);
            copy.addPage(importPage);


            File sdCardDir_WaterImage = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOWNLOADS), folderName_WaterImage);

            String imagePath1 = sdCardDir_WaterImage + "/" + "Image" + id + "_1";
            String imagePath2 = sdCardDir_WaterImage + "/" + "Image" + id + "_2";
            //插入现场图片
            Image image1 = Image.getInstance(imagePath1);
            doc.add(image1);
            Image image2 = Image.getInstance(imagePath2);
            doc.add(image2);

            doc.close();

            Toast.makeText(this, "导出pdf完成", Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            System.out.println(1);
        } catch (BadPdfFormatException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

 

好的,以下是一个使用iText PDF模板Android例子: 1. 首先,添加iText依赖项到你的项目的build.gradle文件中: ``` implementation 'com.itextpdf:itextpdf:5.5.13.2' ``` 2. 在你的应用程序中创建一个PDF模板文件,例如template.pdf。可以使用Adobe Acrobat等PDF编辑器创建模板。 3. 创建一个新的Android Activity,在其中添加以下代码: ``` import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.itextpdf.text.Document; import com.itextpdf.text.Image; import com.itextpdf.text.pdf.PdfContentByte; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfStamper; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class MainActivity extends AppCompatActivity { private Button btnGenerate; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnGenerate = findViewById(R.id.btn_generate); btnGenerate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { generatePDF(); } }); } private void generatePDF() { //模板文件路径 String templatePath = Environment.getExternalStorageDirectory() + "/template.pdf"; //生成PDF文件路径 String pdfPath = Environment.getExternalStorageDirectory() + "/output.pdf"; try { //读取模板文件 PdfReader reader = new PdfReader(templatePath); //在PDF文件上添加内容 PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(pdfPath)); //获取PDF的页面 PdfContentByte canvas = stamper.getOverContent(1); //添加文本 canvas.beginText(); canvas.moveText(100, 500); canvas.setFontAndSize(BaseFont.createFont(), 12); canvas.showText("Hello World"); canvas.endText(); //添加图片 Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image); Image image = Image.getInstance(bitmap, null); image.setAbsolutePosition(100, 400); canvas.addImage(image); //关闭PDF文件 stamper.close(); reader.close(); Toast.makeText(this, "PDF generated successfully", Toast.LENGTH_SHORT).show(); } catch (IOException e) { e.printStackTrace(); Toast.makeText(this, "PDF generation failed", Toast.LENGTH_SHORT).show(); } catch (com.itextpdf.text.DocumentException e) { e.printStackTrace(); Toast.makeText(this, "PDF generation failed", Toast.LENGTH_SHORT).show(); } } } ``` 在这个例子中,我们首先定义了一个模板文件的路径和一个生成PDF文件的路径。然后使用iText的PdfReader和PdfStamper类分别读取模板文件生成PDF文件,并使用PdfContentByte类在PDF文件上添加文本和图片。 注意:需要在AndroidManifest.xml文件中添加存储权限。 希望对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

别具匠心

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值