开发者

Is it possible to convert text into PDF in Android?

开发者 https://www.devze.com 2023-02-27 00:05 出处:网络
I want create a PDF file through my appli开发者_JS百科cation and want to send the PDF file as an attachment by e-mail. Is it possible in Android? If yes please show how.Here is the code

I want create a PDF file through my appli开发者_JS百科cation and want to send the PDF file as an attachment by e-mail. Is it possible in Android? If yes please show how.


Here is the code

    Document doc = new Document();
    PdfWriter.getInstance(doc, new FileOutputStream("urgentz.pdf"));
    doc.open();
    Image image = Image.getInstance ("urgentzImageahslkdhaosd.jpg");
    doc.add(new Paragraph("Your text blah bleh"));
    doc.add(image);               
    doc.close();

Use the iText library with your android project


  1. write following dependency in gradle.build file implementation 'com.itextpdf:itextg:5.5.10'
  2. in AndroidManifest <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  3. In MainActivity write following code

public class MainActivity extends AppCompatActivity { 
Button save;
EditText text;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    save=(Button)findViewById(R.id.save);
    text=(EditText)findViewById(R.id.text);
    save.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(Build.VERSION.SDK_INT> Build.VERSION_CODES.M)
            {
                if(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)== PackageManager.PERMISSION_DENIED)
                {
                    String[] parmission={Manifest.permission.WRITE_EXTERNAL_STORAGE};
                    requestPermissions(parmission,1000);
                }
                else savepdf();
            }
            else savepdf();
        }
    });
}
private  void savepdf()
{
    Document doc=new Document();
    String mfile=new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(System.currentTimeMillis());
    String mfilepath= Environment.getExternalStorageDirectory()+"/"+mfile+".pdf";
    Font smallBold=new Font(Font.FontFamily.TIMES_ROMAN,12,Font.BOLD);
    try{
        PdfWriter.getInstance(doc,new FileOutputStream(mfilepath));
        doc.open();
        String mtext=text.getText().toString();
        doc.addAuthor("harikesh");
        doc.add(new Paragraph(mtext,smallBold));
        doc.close();
        Toast.makeText(this, ""+mfile+".pdf"+" is saved to "+mfilepath, Toast.LENGTH_SHORT).show();
    }
    catch (Exception e)
    {
        Toast.makeText(this,"This is Error msg : " +e.getMessage(), Toast.LENGTH_SHORT).show();
    }

}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode)
    {
        case  1000:
            if(grantResults.length>0 && grantResults[0]== PackageManager.PERMISSION_GRANTED)
            {
                savepdf();
            }
            else Toast.makeText(this, "parmission denied..", Toast.LENGTH_SHORT).show();
    }
}
}`


iText Library Use. Please refer answer Here.

iText sample is many. below refer site. http://www.geek-tutorials.com/java/itext/insert_control_text.php


It is so simple to create the pdf

First download the droidText.0.2.jar and add in gradle file and libs folder if you are using android studio. Then write this code for the PDF

public void createPDF() {
        Document doc = new Document();


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

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

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

            //This is for random name
            number = new ArrayList<Integer>();
            for (int i = 1; i <= 10; ++i) number.add(i);
            Collections.shuffle(number);

            File file = new File(dir, "Document" + number + ".pdf");
            FileOutputStream fOut = new FileOutputStream(file);
            PdfWriter.getInstance(doc, fOut);

            //open the document
            doc.open();

            Paragraph p1 = new Paragraph("TENANTS : " + tenants.getText().toString());
            Font paraFont = new Font(Font.COURIER);
            p1.setAlignment(Paragraph.ALIGN_CENTER);
            p1.setFont(paraFont);

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

            Paragraph p2 = new Paragraph("OFFFER NUMBER : " + offer_number.getText().toString());
            Font paraFont2 = new Font(Font.COURIER, 14.0f, Color.GREEN);
            p2.setAlignment(Paragraph.ALIGN_CENTER);
            p2.setFont(paraFont2);

            doc.add(p2);

            Paragraph p3 = new Paragraph("OFFFER NUMBER : " + offer_number.getText().toString());
            Font paraFont3 = new Font(Font.COURIER, 14.0f, Color.GREEN);
            p3.setAlignment(Paragraph.ALIGN_CENTER);
            p3.setFont(paraFont2);

            doc.add(p3);

            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            Bitmap bitmap = BitmapFactory.decodeResource(getBaseContext().getResources(), R.drawable.logo);
            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("ADUREC DOCUMENT");
            HeaderFooter pdfFooter = new HeaderFooter(footerText, true);
            doc.setFooter(pdfFooter);

//            Toast.makeText(getApplicationContext(), "success pdf", Toast
//                    .LENGTH_LONG).show();

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

    }


Kotlin Sample Code:

You can use below code to create pdf pages and draw anything in canvas.

fun createPdf(textToPdf: String) {

    // create a new document
    val document = PdfDocument()

    // crate a page description
    var pageInfo: PdfDocument.PageInfo = PdfDocument.PageInfo.Builder(300, 600, 1).create()

    // start a page
    var page: PdfDocument.Page = document.startPage(pageInfo)
    var canvas = page.canvas
    var paint = Paint()
    paint.color = Color.RED
    canvas.drawCircle(50F, 50F, 30F, paint)
    paint.color = Color.BLACK
    canvas.drawText(textToPdf, 80F, 50F, paint)
    //canvas.drawt
    // finish the page
    document.finishPage(page)
    // draw text on the graphics object of the page

    // Create Page 2
    pageInfo = PdfDocument.PageInfo.Builder(300, 600, 2).create()
    page = document.startPage(pageInfo)
    canvas = page.canvas
    paint = Paint()
    paint.color = Color.BLUE
    canvas.drawCircle(100F, 100F, 100F, paint)
    document.finishPage(page)

    // write the document content
    val directory_path = Environment.getExternalStorageDirectory().path + "/mypdf/"
    val file = File(directory_path)
    if (!file.exists()) {
        file.mkdirs()
    }
    val targetPdf = directory_path + "test-2.pdf"
    val filePath = File(targetPdf)
    try {
        document.writeTo(FileOutputStream(filePath))
        Toast.makeText(mContext, "Done", Toast.LENGTH_LONG).show()
    } catch (e: IOException) {
        Log.e("main", "error " + e.toString())
        Toast.makeText(mContext, "Something wrong: " + e.toString(), Toast.LENGTH_LONG).show()
    }

    // close the document
    document.close()
    //isPrinting = false
}

Note:

Do not forget to add external storage write permission

0

精彩评论

暂无评论...
验证码 换一张
取 消