Simple library to generate and view PDF in Android

Overview

PDFCreatorAndroid

Simple library to generate and view PDF in Android


Android Arsenal


Cover

A simple library to create and view PDF with zero dependency Or native code.

Add it in your root build.gradle at the end of repositories:

	allprojects {
		repositories {
			...
			maven { url 'https://jitpack.io' }
		}
	}

Step 2. Add the dependency

	dependencies {
	        implementation 'com.github.tejpratap46:PDFCreatorAndroid:LATEST_RELEASE'
	}

Try It

Download From Play Store

Concept

  • Android has capability to print documents to PDF, this library simplifies those API's to generate PDF easily.
  • At basic level, API renders Views to PDF. To create A PDF with pages we need to submit views exactly height of one page, any view larges then that that will be trimmed.
  • This library creates pages by adding views to a parent view unitil the next view is about to exceed current page. If next view exceeds current page, that view will be added to new page.

Implementation

  1. PDF creater uses views which can be rendered, So we need to exted an activity in order to create activity.
  2. Create a Empty Activity without any layout and extend it with PDFCreatorActivity. Do not set use setContentView(int resourceId) inside your created activity.
  3. There are 3 abstract methods you have to override.
    1. getHeaderView()
      • This will be header for PDF and will be added to each page. (Accepts PDFHeaderView)
    2. getBodyViews()
      • This will return a PDFBody which consist of list of views which can be broken between pages.
    3. getFooterView()
      • This will be footer for PDF and will be added to each page. (Accepts PDFFooterView)
    4. getWatermarkView()
      • [OPTIONAL] This add a watermark image to each page. (Accepts PDFImageView), see issue #14
    5. onNextClicked()
      • This is a handler method to get callback when user taps on Next.
  4. In onCreate of you activity, you have to call createPDF(String fileName, PDFUtilListener listener). It will generate PDF and give you a PDF file in callback (if success). After receiving callback you can close activity and do whatever you need to do with PDF.
  5. This library also provides PDFUtil.pdfToBitmap(File pdfFile) method to get image preview of all pages of sepcified PDF file.

Available Views

  1. TextView -> PDFTextView
  2. VerticalView -> PDFVerticalView
  3. HorizontalView -> PDFHorizontalView
  4. ImageView -> PDFImageView
  5. TableView -> PDFTableView
  6. Saperator -> PDFLineSaperatorView

Advanced

If you cannot find some methods of a View Class inside PDFView class you can get view by calling pdfView.getView() on any available PDFView class and then update view properties.

For example Android TextView support setting html to TextView which is not available in PDFTextView, to do that see example below:

PDFTextView pdfIconLicenseView = new PDFTextView(getApplicationContext(), PDFTextView.PDF_TEXT_SIZE.H3);
Spanned icon8Link = Html.fromHtml("Icon from <a href='https://icons8.com'>https://icons8.com</a>");
pdfIconLicenseView.getView().setText(icon8Link);

Another example, Set gravity to View

pdfIconLicenseView.getView().setGravity(Gravity.CENTER_VERTICAL);

Advanced, Proceed with caution ⚠️

This is a unfinished feature, Use only for basic cases [After using this feature you cannot add child view to your custom view]. If you want to add a custom view to PDF (such as chart or icon), you just can create your own like this:

PDFVerticalView verticalView = new PDFVerticalView(context);
verticalView.setView(View view);

Example:

An example is created, Look at PdfCreatorActivity of app.

VIEWS

  • PDFVerticalView
PDFVerticalView verticalView = new PDFVerticalView(getApplicationContext());
PDFTextView pdfTextView1 = new PDFTextView(getApplicationContext(), PDFTextView.PDF_TEXT_SIZE.P)
				.setText("TextView1");
verticalView.addView(pdfTextView1)
PDFTextView pdfTextView2 = new PDFTextView(getApplicationContext(), PDFTextView.PDF_TEXT_SIZE.P)
				.setText("TextView2");
verticalView.addView(pdfTextView2)
// Get View
LinearLayout layout = verticalView.getView();
  • PDFHorizontalView
PDFHorizontalView horizontalView = new PDFHorizontalView(getApplicationContext());
PDFTextView pdfTextView1 = new PDFTextView(getApplicationContext(), PDFTextView.PDF_TEXT_SIZE.P)
				.setText("TextView1");
horizontalView.addView(pdfTextView1)
PDFTextView pdfTextView2 = new PDFTextView(getApplicationContext(), PDFTextView.PDF_TEXT_SIZE.P)
				.setText("TextView2");
horizontalView.addView(pdfTextView2)
// Get View
LinearLayout layout = horizontalView.getView();
  • PDFTextView
PDFTextView pdfTextView1 = new PDFTextView(getApplicationContext(), PDFTextView.PDF_TEXT_SIZE.P)
				.setText("TextView1");
PDFTextView pdfTextView2 = new PDFTextView(getApplicationContext(), PDFTextView.PDF_TEXT_SIZE.P)
				.setText(new SpanningString("TextView2"));
// Get View
TextView textView = pdfTextView2.getView();
  • PDFImageView
PDFImageView pdfImageView = new PDFImageView(getApplicationContext(), PDFTextView.PDF_TEXT_SIZE.P)
				.setImageResource(R.drawable.ic_example);
// Get View
ImageView imageView = pdfImageView.getView();
  • PDFTableView
String[] textInTable = {"1", "2", "3", "4"};

// Create table column headers
PDFTableView.PDFTableRowView tableHeader = new PDFTableView.PDFTableRowView(getApplicationContext());
for (String s : textInTable) {
    PDFTextView pdfTextView = new PDFTextView(getApplicationContext(), PDFTextView.PDF_TEXT_SIZE.P);
    pdfTextView.setText("Header Title: " + s);
    tableHeader.addToRow(pdfTextView);
}
// Create first row
PDFTableView.PDFTableRowView tableRowView1 = new PDFTableView.PDFTableRowView(getApplicationContext());
for (String s : textInTable) {
    PDFTextView pdfTextView = new PDFTextView(getApplicationContext(), PDFTextView.PDF_TEXT_SIZE.P);
    pdfTextView.setText("Row 1 : " + s);
    tableRowView1.addToRow(pdfTextView);
}

// PDFTableView takes table header and first row at once because if page ends after adding header then first row will be on next page. To avoid confusion to user, table header and first row is printed together.
PDFTableView tableView = new PDFTableView(getApplicationContext(), tableHeader, tableRowView1);
for (int i = 0; i < 10; i++) {
    // Create 10 rows and add to table.
    PDFTableView.PDFTableRowView tableRowView = new PDFTableView.PDFTableRowView(getApplicationContext());
    for (String s : textInTable) {
	PDFTextView pdfTextView = new PDFTextView(getApplicationContext(), PDFTextView.PDF_TEXT_SIZE.P);
	pdfTextView.setText("Row " + (i + 1) + ": " + s);
	tableRowView.addToRow(pdfTextView);
    }
    tableView.addRow(tableRowView);
}
  • PDFLineSeparatorView
PDFLineSeparatorView lineSeparatorWhite = new PDFLineSeparatorView(getApplicationContext()).setBackgroundColor(Color.WHITE);
PDFLineSeparatorView lineSeparatorBlack = new PDFLineSeparatorView(getApplicationContext()).setBackgroundColor(Color.BLACK);
// Get View
View separatorView = lineSeparatorWhite.getView();

Pdf Viewer

This library now has a built-in Pdf Reader which uses PDFUtil.pdfToBitmap(savedPDFFile) internally to show preview of Pdf as Images inside a View Pager, Pdf viewer also has a RecyclerView version as well, but you need to add RecyclerView as Your Dependency. To Use ViewPager Based Pdf Viewer, you just have to create a Activity and extend it with PDFViewerActivity and call it using an Intent.

Uri pdfUri = Uri.fromFile(savedPDFFile);

Intent intentPdfViewer = new Intent(MainActivity.this, PdfViewerActivity.class);
intentPdfViewer.putExtra(PdfViewerActivity.PDF_FILE_URI, pdfUri);

startActivity(intentPdfViewer);

You can see Example Code At: PdfViewerActivity of app.

Html To Pdf

You can create a Pdf from Html using Utility function PDFUtil.generatePDFFromHTML(getApplicationContext(), pdfFileToSave, "<html string />", callback);

// Create Temp File to save Pdf To
final File savedPDFFile = FileManager.getInstance().createTempFile(getApplicationContext(), "pdf", false);
// Generate Pdf From Html
PDFUtil.generatePDFFromHTML(getApplicationContext(), savedPDFFile, " <!DOCTYPE html>\n" +
    "<html>\n" +
    "<body>\n" +
    "\n" +
    "<h1>My First Heading</h1>\n" +
    "<p>My first paragraph.</p>\n" +
    " <a href='https://www.example.com'>This is a link</a>" +
    "\n" +
    "</body>\n" +
    "</html> ", new PDFPrint.OnPDFPrintListener() {
        @Override
        public void onSuccess(File file) {
            // Open Pdf Viewer
            Uri pdfUri = Uri.fromFile(savedPDFFile);

            Intent intentPdfViewer = new Intent(MainActivity.this, PdfViewerActivity.class);
            intentPdfViewer.putExtra(PdfViewerActivity.PDF_FILE_URI, pdfUri);

            startActivity(intentPdfViewer);
        }

        @Override
        public void onError(Exception exception) {
            exception.printStackTrace();
        }
});

WebView To Pdf

With this feature, you can directly create Pdf from whatever your WebView is showing. You can add contenteditable="true" and have user edit data and create pdf from edited Data. You can just call Utility function: PDFUtil.generatePDFFromWebView(savedPDFFile, webView, callback)

You can see Example Code At: PdfEditorActivity of app.

// Create Temp File to save Pdf To
final File savedPDFFile = FileManager.getInstance().createTempFile(getApplicationContext(), "pdf", false);
// Generate Pdf From Html
PDFUtil.generatePDFFromWebView(savedPDFFile, webView, new PDFPrint.OnPDFPrintListener() {
    @Override
    public void onSuccess(File file) {
        // Open Pdf Viewer
        Uri pdfUri = Uri.fromFile(savedPDFFile);

        Intent intentPdfViewer = new Intent(PdfEditorActivity.this, PdfViewerActivity.class);
        intentPdfViewer.putExtra(PdfViewerActivity.PDF_FILE_URI, pdfUri);

        startActivity(intentPdfViewer);
    }

    @Override
    public void onError(Exception exception) {
        exception.printStackTrace();
    }
});

Example PDF

Donate

ko-fi

Comments
  • Multiple page pdf not creating as CurrentpageHeight and viewitem.getHeight is always 0

    Multiple page pdf not creating as CurrentpageHeight and viewitem.getHeight is always 0

    Hi , Please check the below line where CurrentpageHeight and viewitem.getHeight is always 0

    https://github.com/tejpratap46/PDFCreatorAndroid/blob/ffd0c31b1b3d29a4101ff62fbed9b073f0429b8c/pdfcreator/src/main/java/com/tejpratapsingh/pdfcreator/activity/PDFCreatorActivity.java#L193

    opened by wahdatjan 12
  •  Pdf Generator Issue -table view

    Pdf Generator Issue -table view

    I integrated your pdf library in my project. It was working fine when viewing pdf and share. But without viewing i want only share pdf.

    Childview tableview coming one row in one page.

    please find code for reference

    public void createPDFOverall(final String fileName, final PDFUtil.PDFUtilListener pdfUtilListener) {
            // Create parent RelativeLayout
            layoutPageParent = new LinearLayout(this.ctx);
            LinearLayout.LayoutParams relParentParam = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            layoutPageParent.setLayoutParams(relParentParam);
            final ArrayList<View> bodyViewList = new ArrayList<>();
            View header = null;
            if (getHeaderView(0) != null) {
                header = getHeaderView(0).getView();
                header.setTag(PDFHeaderView.class.getSimpleName());
                bodyViewList.add(header);
                addViewToTempLayout(layoutPageParent, header);
            }
    
            if (getBodyViews() != null) {
                for (PDFView pdfView : getBodyViews().getChildViewList()) {
                    View bodyView = pdfView.getView();
                    bodyView.setTag(PDFBody.class.getSimpleName());
                    bodyViewList.add(bodyView);
                    addViewToTempLayout(layoutPageParent, bodyView);
                }
            }
    
    
            final Handler handler = new Handler(Looper.getMainLooper());
            final View finalHeader = header;
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    createPDFFromViewList(finalHeader, bodyViewList, fileName, new PDFUtil.PDFUtilListener() {
                        @Override
                        public void pdfGenerationSuccess(File savedPDFFile) {
                            try {
    //                    pagePreviewBitmapList.clear();
    //                    pagePreviewBitmapList.addAll(PDFUtil.pdfToBitmap(savedPDFFile));
    //                    textViewGeneratingPDFHolder.setVisibility(View.GONE);
    //                    layoutPrintPreview.setVisibility(View.VISIBLE);
                                selectedPreviewPage = 0;
    //                    imageViewPDFPreview.setImageBitmap(pagePreviewBitmapList.get(selectedPreviewPage));
    //                    textViewPageNumber.setText(String.format(Locale.getDefault(), "%d of %d", selectedPreviewPage + 1, pagePreviewBitmapList.size()));
                            } catch (Exception e) {
                                e.printStackTrace();
    //                    imageViewPDFPreview.setVisibility(View.GONE);
    //                    textViewPageNumber.setVisibility(View.GONE);
    //                    buttonNextPage.setVisibility(View.GONE);
    //                    buttonPreviousPage.setVisibility(View.GONE);
    //                    textViewPreviewNotAvailable.setVisibility(View.VISIBLE);
                            }
                            savedPDFFilec = savedPDFFile;
                            pdfUtilListener.pdfGenerationSuccess(savedPDFFile);
                        }
    
                        @Override
                        public void pdfGenerationFailure(Exception exception) {
                            pdfUtilListener.pdfGenerationFailure(exception);
                        }
                    });
                }
            }, 1000);
    
        }
    
    
        /**
         * Creates a paginated PDF page views from list of views those are already rendered on screen
         * (Only rendered views can give height)
         *
         * @param tempViewList list of views to create pdf views from, view should be already rendered to screen
         */
        private void createPDFFromViewList(final View headerView, @NonNull final ArrayList<View> tempViewList, @NonNull final String filename, final PDFUtil.PDFUtilListener pdfUtilListener) {
            tempViewList.get(tempViewList.size() - 1).post(new Runnable() {
                @Override
                public void run() {
    
                    // Clean temp folder
                    final FileManager myOPDFileManager = FileManager.getInstance();
                    myOPDFileManager.cleanTempFolder(ctx);
    
                    ((Activity) ctx).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            final List<View> pdfPageViewList = new ArrayList<>();
    //                        LinearLayout currentPDFLayout = (LinearLayout) ((Activity) ctx).getLayoutInflater().inflate(com.tejpratapsingh.pdfcreator.R.layout.item_pdf_page, null);
    //                        currentPDFLayout.setBackgroundColor(ContextCompat.getColor(ctx.getApplicationContext(), com.tejpratapsingh.pdfcreator.R.color.colorWhite));
    //                        pdfPageViewList.add(currentPDFLayout);
                            int currentPageHeight = 0;
    
                            if (headerView != null) {
                                // If item is a page header, store its height so we can add it to all pages without waiting to render it every time
                                headerLayoutHeight = headerView.getHeight();
    //                            headerLayoutHeight = 50;
                            }
    
                            int pageIndex = 1;
                            LinearLayout currentPDFLayout = null;
                            for (View viewItem : tempViewList) {
                                if (currentPageHeight + 848 > (ctx.getResources().getDimensionPixelSize(com.tejpratapsingh.pdfcreator.R.dimen.pdf_height)
                                        - (ctx.getResources().getDimensionPixelSize(com.tejpratapsingh.pdfcreator.R.dimen.pdf_margin_vertical) * 2))) {
                                    currentPDFLayout = (LinearLayout) ((Activity) ctx).getLayoutInflater().inflate(com.tejpratapsingh.pdfcreator.R.layout.item_pdf_page, null);
                                    currentPDFLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                                            LinearLayout.LayoutParams.WRAP_CONTENT));
                                    currentPDFLayout.setBackgroundColor(ContextCompat.getColor(ctx.getApplicationContext(), com.tejpratapsingh.pdfcreator.R.color.colorWhite));
                                    pdfPageViewList.add(currentPDFLayout);
    
                                    currentPageHeight = 0;
    
                                    // Add page header again
                                    if (headerLayoutHeight > 0) {
                                        // If height is available, only then add header
                                        LinearLayout layoutHeader = getHeaderView(pageIndex).getView();
                                        addViewToTempLayout(layoutPageParent, layoutHeader);
                                        currentPageHeight += headerLayoutHeight;
                                        layoutPageParent.removeView(layoutHeader);
                                        currentPDFLayout.addView(layoutHeader);
    
                                        pageIndex = pageIndex + 1;
                                    }
                                    currentPageHeight += viewItem.getHeight();
                                    if (viewItem.getParent() != null) {
                                        ((ViewGroup) viewItem.getParent()).removeView(viewItem); // <- fix
                                    }
                                    currentPDFLayout.addView(viewItem);
                                }
    
    
                            }
    
                            PDFUtil.getInstance().generatePDF(pdfPageViewList, myOPDFileManager.createTempFileWithName(ctx.getApplicationContext(), filename + ".pdf", false).getAbsolutePath(), pdfUtilListener);
                        }
                    });
                }
            });
        }
    
    //    protected abstract PDFHeaderView getHeaderView(int page);
    //
    //    protected abstract PDFBody getBodyViews();
    
    
        protected PDFHeaderView getHeaderView(int pageIndex) {
            PDFHeaderView headerView = new PDFHeaderView(ctx);
    
    
    //        PDFTextView pdfTextViewPage = new PDFTextView(ctx, PDFTextView.PDF_TEXT_SIZE.SMALL);
    //        pdfTextViewPage.setText(String.format(Locale.getDefault(), "Page: %d", pageIndex + 1));
    //        pdfTextViewPage.setLayout(new LinearLayout.LayoutParams(
    //                LinearLayout.LayoutParams.MATCH_PARENT,
    //                LinearLayout.LayoutParams.MATCH_PARENT, 0));
    //        pdfTextViewPage.getView().setGravity(Gravity.END);
    //
    //        headerView.addView(pdfTextViewPage);
    
    
            PDFHorizontalView horizontalViewLogo = new PDFHorizontalView(ctx);
    
            PDFImageView imageView = new PDFImageView(ctx);
            LinearLayout.LayoutParams imageLayoutParam = new LinearLayout.LayoutParams(100,
                    100);
    //        imageView.setImageScale(ImageView.ScaleType.CENTER_INSIDE);
            imageView.setImageResource(R.mipmap.ic_launcher);
            imageLayoutParam.setMargins(0, 0, 10, 0);
            imageView.setLayout(imageLayoutParam);
            horizontalViewLogo.addView(imageView);
            horizontalViewLogo.getView().setGravity(Gravity.CENTER_HORIZONTAL);
            headerView.addView(horizontalViewLogo);
    
            PDFHorizontalView horizontalView = new PDFHorizontalView(ctx);
    
    
            PDFTextView pdfTextView = new PDFTextView(ctx, PDFTextView.PDF_TEXT_SIZE.HEADER);
    //        SpannableString word = new SpannableString(" Transaction Detail Statement\n");
    //        word.setSpan(new ForegroundColorSpan(Color.DKGRAY), 0, word.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            pdfTextView.setText(" Transaction Detail Statement");
            pdfTextView.setTextColor(Color.BLUE);
            pdfTextView.setLayout(new LinearLayout.LayoutParams(
                    0,
                    LinearLayout.LayoutParams.WRAP_CONTENT, 1));
            pdfTextView.getView().setGravity(Gravity.CENTER);
            pdfTextView.getView().setTypeface(pdfTextView.getView().getTypeface(), Typeface.BOLD);
            horizontalView.addView(pdfTextView);
            headerView.addView(horizontalView);
    
            PDFTextView pdfCompanyNameView = new PDFTextView(ctx, PDFTextView.PDF_TEXT_SIZE.H3);
            pdfCompanyNameView.setText("Company Namennnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn");
            pdfTextView.setLayout(new LinearLayout.LayoutParams(
                    0,
                    LinearLayout.LayoutParams.WRAP_CONTENT, 1));
            headerView.addView(pdfCompanyNameView);
    
            PDFTextView pdfAddressView = new PDFTextView(ctx, PDFTextView.PDF_TEXT_SIZE.P);
            pdfTextView.setLayout(new LinearLayout.LayoutParams(
                    0,
                    LinearLayout.LayoutParams.WRAP_CONTENT, 1));
            pdfAddressView.setText("Address Line 1\nCity, State - 123456");
            headerView.addView(pdfAddressView);
    
    
            PDFHorizontalView pdfHorizontalViewR4 = new PDFHorizontalView(ctx);
            PDFHorizontalView pdfHorizontalViewR5 = new PDFHorizontalView(ctx);
            PDFHorizontalView pdfHorizontalViewR6 = new PDFHorizontalView(ctx);
            PDFTextView filter1View = new PDFTextView(ctx, PDFTextView.PDF_TEXT_SIZE.P, false, "");
            SpannableString filter1SS = new SpannableString("Filter");
            filter1SS.setSpan(new ForegroundColorSpan(Color.WHITE), 0, filter1SS.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            filter1View.setText(filter1SS);
            filter1View.getView().setBackgroundColor(ctx.getResources().getColor(R.color.grey_500));
            filter1View.setLayout(new LinearLayout.LayoutParams(0,
                    LinearLayout.LayoutParams.WRAP_CONTENT, 1));
            filter1View.getView().setGravity(Gravity.CENTER);
            filter1View.getView().setTypeface(filter1View.getView().getTypeface(), Typeface.NORMAL);
    
            PDFTextView filterSpaceView = new PDFTextView(ctx, PDFTextView.PDF_TEXT_SIZE.P, false, "");
            SpannableString spaceSS = new SpannableString(" ");
            spaceSS.setSpan(new ForegroundColorSpan(Color.WHITE), 0, spaceSS.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            filterSpaceView.setText(spaceSS);
            filterSpaceView.getView().setBackgroundColor(ctx.getResources().getColor(R.color.colorWhite));
            filterSpaceView.setLayout(new LinearLayout.LayoutParams(3,
                    LinearLayout.LayoutParams.WRAP_CONTENT));
            filterSpaceView.getView().setGravity(Gravity.CENTER);
            filterSpaceView.getView().setTypeface(filterSpaceView.getView().getTypeface(), Typeface.NORMAL);
    
            PDFTextView filter2View = new PDFTextView(ctx, PDFTextView.PDF_TEXT_SIZE.P, false, "");
            SpannableString filter2SS = new SpannableString("Period");
            filter2SS.setSpan(new ForegroundColorSpan(Color.WHITE), 0, filter2SS.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            filter2View.setText(filter2SS);
            filter2View.getView().setBackgroundColor(ctx.getResources().getColor(R.color.grey_500));
            filter2View.setLayout(new LinearLayout.LayoutParams(0,
                    LinearLayout.LayoutParams.WRAP_CONTENT, 1));
            filter2View.getView().setGravity(Gravity.CENTER);
            filter2View.getView().setTypeface(filter2View.getView().getTypeface(), Typeface.NORMAL);
    
            pdfHorizontalViewR4.addView(filter1View);
            pdfHorizontalViewR4.addView(filterSpaceView);
            pdfHorizontalViewR4.addView(filter2View);
    
            PDFTextView filter3View = new PDFTextView(ctx, PDFTextView.PDF_TEXT_SIZE.P, false, "");
            SpannableString filter3SS = new SpannableString("filter");
            filter3SS.setSpan(new ForegroundColorSpan(Color.WHITE), 0, filter3SS.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            filter3View.setText(filter3SS);
            filter3View.getView().setBackgroundColor(ctx.getResources().getColor(R.color.grey_500));
            filter3View.setLayout(new LinearLayout.LayoutParams(0,
                    LinearLayout.LayoutParams.WRAP_CONTENT, 1));
            filter3View.getView().setGravity(Gravity.CENTER);
            filter3View.getView().setTypeface(filter3View.getView().getTypeface(), Typeface.NORMAL);
    
            PDFTextView filterSpace1View = new PDFTextView(ctx, PDFTextView.PDF_TEXT_SIZE.P, false, "");
            SpannableString space1SS = new SpannableString(" ");
            space1SS.setSpan(new ForegroundColorSpan(Color.WHITE), 0, space1SS.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            filterSpace1View.setText(space1SS);
            filterSpace1View.getView().setBackgroundColor(ctx.getResources().getColor(R.color.colorWhite));
            filterSpace1View.setLayout(new LinearLayout.LayoutParams(3,
                    LinearLayout.LayoutParams.WRAP_CONTENT));
            filterSpace1View.getView().setGravity(Gravity.CENTER);
            filterSpace1View.getView().setTypeface(filterSpace1View.getView().getTypeface(), Typeface.NORMAL);
    
            PDFTextView filter4View = new PDFTextView(ctx, PDFTextView.PDF_TEXT_SIZE.P, false, "");
            SpannableString filter4SS = new SpannableString("Period");
            filter4SS.setSpan(new ForegroundColorSpan(Color.WHITE), 0, filter4SS.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            filter4View.setText(filter4SS);
            filter4View.getView().setBackgroundColor(ctx.getResources().getColor(R.color.grey_500));
            filter4View.setLayout(new LinearLayout.LayoutParams(0,
                    LinearLayout.LayoutParams.WRAP_CONTENT, 1));
            filter4View.getView().setGravity(Gravity.CENTER);
            filter4View.getView().setTypeface(filter4View.getView().getTypeface(), Typeface.NORMAL);
    
            pdfHorizontalViewR5.addView(filter3View);
            pdfHorizontalViewR5.addView(filterSpace1View);
            pdfHorizontalViewR5.addView(filter4View);
    
            String[] textInTable = {"Transaction ID", "Mobile Number", "Cash Back \n(MMK)", "Opening Balance \n(MMK)", "Credit \n(MMK)", "Debit \n(MMK)", "Closing Balance \n(MMK)", "Date & Time"};
            for (String title : textInTable) {
                PDFTextView headerTitleView = new PDFTextView(ctx, PDFTextView.PDF_TEXT_SIZE.P, false, "");
                headerTitleView.setLayout(new LinearLayout.LayoutParams(0,
                        40, 1));
                headerTitleView.setText(title);
                headerTitleView.getView().setTextSize(4f);
                headerTitleView.setTextColor(ctx.getResources().getColor(R.color.colorWhite));
                headerTitleView.getView().setGravity(Gravity.CENTER);
    //            if (!title.equals("Date & Time"))
    //                headerTitleView.setBackground(ctx.getResources().getDrawable(R.drawable.right_vertical_line));
    //            else
                headerTitleView.setBackgroundColor(ctx.getResources().getColor(R.color.blue_700));
                pdfHorizontalViewR6.addView(headerTitleView);
            }
    
            headerView.addView(pdfHorizontalViewR4);
            headerView.addView(pdfHorizontalViewR5);
            headerView.addView(pdfHorizontalViewR6);
    
            PDFLineSeparatorView lineSeparatorView1 = new PDFLineSeparatorView(ctx).setBackgroundColor(Color.WHITE);
            headerView.addView(lineSeparatorView1);
    
    
            return headerView;
        }
    
        protected PDFBody getBodyViews() {
            PDFBody pdfBody = new PDFBody();
    
    
            String[] textInTable = {"1", "2", "3", "4", "5", "6", "7", "8"};
    
    //        PDFLineSeparatorView lineSeparatorView2 = new PDFLineSeparatorView(ctx).setBackgroundColor(Color.WHITE);
    //        pdfBody.addView(lineSeparatorView2);
    //        PDFTextView pdfTableTitleView = new PDFTextView(ctx, PDFTextView.PDF_TEXT_SIZE.P);
    //        pdfTableTitleView.setText("");
    //        pdfBody.addView(pdfTableTitleView);
    
    //        String[] textInTableHeader = {"Transaction ID", "Mobile Number", "Cash Back \n(MMK)", "Opening Balance \n(MMK)", "Credit \n(MMK)", "Debit \n(MMK)", "Closing Balance \n(MMK)", "Date & Time"};
    
            PDFTableView.PDFTableRowView tableHeader = new PDFTableView.PDFTableRowView(ctx);
           /* for (String s : textInTableHeader) {
                PDFTextView pdfTextView = new PDFTextView(ctx, PDFTextView.PDF_TEXT_SIZE.P);
                pdfTextView.setText(textInTableHeader[s]);
                tableHeader.addToRow(pdfTextView);
            }*/
    
          /*  for (int kl = 0; kl < textInTableHeader.length; kl++) {
                PDFTextView pdfTextView = new PDFTextView(ctx, PDFTextView.PDF_TEXT_SIZE.P);
                pdfTextView.setText(textInTableHeader[kl]);
                pdfTextView.getView().setGravity(Gravity.CENTER);
                tableHeader.addToRow(pdfTextView);
            }*/
    
            String[] textInTableContent = {"1771662528", "(+91)9500465992", "  ဦးသက္နုိင္ဦး", "5,536.59", "2", "-", "5,537.59", "Mon, 07-Sep-2020 19:07:19"};
    
            PDFTableView.PDFTableRowView tableRowView = new PDFTableView.PDFTableRowView(ctx);
            tableRowView.setLayout(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                    30));
            PDFTableView tableView = new PDFTableView(ctx, tableHeader, tableRowView);
    
            for (int i = 0; i < 40; i++) {
                // Create 10 rows
                PDFTableView.PDFTableRowView tableRowView1 = new PDFTableView.PDFTableRowView(ctx);
                PDFTableView.PDFTableRowView tableRowView2 = new PDFTableView.PDFTableRowView(ctx);
                tableRowView1.setLayout(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                        30));
                tableRowView2.setLayout(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                        1));
                tableRowView2.setBackgroundColor(ctx.getResources().getColor(R.color.colorBlack));
                /*  for (String s : textInTable) {
                    PDFTextView pdfTextView = new PDFTextView(ctx, PDFTextView.PDF_TEXT_SIZE.P);
                    pdfTextView.setText("Row " + (i + 2) + ": " + s);
                    tableRowView.addToRow(pdfTextView);
                }*/
                for (int j = 0; j < 1; j++) {
    
                    for (int k = 0; k < textInTableContent.length; k++) {
                        PDFTextView pdfTextView = new PDFTextView(ctx, PDFTextView.PDF_TEXT_SIZE.P);
                        pdfTextView.setText(i + textInTableContent[k]);
                        pdfTextView.getView().setGravity(Gravity.CENTER);
                        tableRowView1.addToRow(pdfTextView);
                    }
                }
                tableView.addRow(tableRowView1);
                tableView.addRow(tableRowView2);
    
    
            }
    
            pdfBody.addView(tableView);
    
            PDFLineSeparatorView lineSeparatorView3 = new PDFLineSeparatorView(ctx).setBackgroundColor(Color.BLACK);
            pdfBody.addView(lineSeparatorView3);
    
    //        PDFTextView pdfIconLicenseView = new PDFTextView(ctx, PDFTextView.PDF_TEXT_SIZE.H3);
    //        Spanned icon8Link = Html.fromHtml("Icon from <a href='https://icons8.com'>https://icons8.com</a>");
    //        pdfIconLicenseView.getView().setText(icon8Link);
    //        pdfBody.addView(pdfIconLicenseView);
    
            return pdfBody;
        }
    
    opened by sakaravinth 10
  • Table Column Alignment & Repeating header

    Table Column Alignment & Repeating header

    Hi Tej,

    thank you for creating and maintaining this library.

    I have been able to use and generate a pdf. It contains a table that extends to 2 or more pages. I have two issues can you please guide

    1. Since the table repeats on two or more pages - how can the table headers be repeated?
    2. How to assign table column width - I have 2 columns, and I need the first to be on the left and seond on the right - justified...

    Please guide

    Thanks

    opened by madhall 5
  • Could not Share with other apps like GMail in Android 11

    Could not Share with other apps like GMail in Android 11

    We could not share the pdf with other apps. As the pdf is stored in the app specific storage and Android 11 restrict this access. https://developer.android.com/about/versions/11/privacy/storage

    bug 
    opened by Rathieshr 5
  • cannot resize entire row depending on the value in textviews

    cannot resize entire row depending on the value in textviews

    I was trying to create a table view, but the values in each text view in the table view might vary. so need the entire row to resize depending on the value present in the text view. if you can see the first header row I just added some characters to the first text view, the rest columns does not match the height to the first row. tried adding layout params to text view and the row. same issue persists.

    image

    int[] widthPercent2 = {5, 12, 17, 10, 10, 10, 10, 10, 8, 8};
       String[] headerTitle2 = {"S# fjtdhrdygkyftjf", "Item Code", "Item Name", "Cs Qty", "Pc Qty", "Cs Price", "Pc Price", "Sub Total", "VAT", "Total"};
       String[] childTitle1 = {"1", itemCode[0], itemName[0], csQty[0], pcQty[0], csPrice[0], pcPrice[0], subtotal[0], vat[0], total[0]};
    
    private PDFTableView.PDFTableRowView createTableHeader(String[] headerTitle) {
           PDFTableView.PDFTableRowView tableHeaderRow = new PDFTableView.PDFTableRowView(getApplicationContext());
           for (int i = 0; i < headerTitle.length; i++) {
               tableHeaderRow.addToRow(createHeaderColumn(headerTitle[i], i));
           }
           tableHeaderRow.setLayout(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT));
           return tableHeaderRow;
       }
    
    private PDFTextView createHeaderColumn(String title, int pos) {
           PDFTextView pdfTextView = new PDFTextView(getApplicationContext(), PDFTextView.PDF_TEXT_SIZE.P).setText(title);
           if (pos == 0) {
               pdfTextView.getView().setBackground(getResources().getDrawable(R.drawable.border_left_top_right_grey));
           } else {
               pdfTextView.getView().setBackground(getResources().getDrawable(R.drawable.border_top_right_grey));
           }
    
    
           pdfTextView.getView().setTextSize(TypedValue.COMPLEX_UNIT_SP,  (float) 3.5);
           pdfTextView.setTextTypeface(ResourcesCompat.getFont(getApplicationContext(), R.font.calibrib));
           pdfTextView.setPadding(10, 0, 0, 0);
           pdfTextView.setLayout(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
           return pdfTextView;
       }
    

    I attach the row to the table using the below mentioned code

    PDFTableView tableView = new PDFTableView(getApplicationContext(), createTableHeader(headerTitleInv),
                    createTableChildFirstRow(childTitleInv, 1));
            tableView.setColumnWidth(widthPercentInv);
            pdfBody.addView(tableView);
            pdfBody.addView(createSeparator(Color.WHITE, 15));
    
    

    Could anyone tell me what I'm doing wrong/missing out..

    opened by turbosoft-anudeep 4
  • Null Pointer Error when using setImageBitmap for ImageView

    Null Pointer Error when using setImageBitmap for ImageView

    Hi,

    I am trying to display an image from the gallery using Mediastore but when I run the below code, the pdf doesnt launch but crashes with an error saying below. Can you please guide? It is the only issue with launching this feature... inability to display image from gallery on pdf.

       java.lang.NullPointerException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkNotNullParameter, parameter exception
            at in.trial.trial.Invoicing.ui.downloadInvoicePdf$onCreate$1.pdfGenerationFailure(Unknown Source:2)
            at com.tejpratapsingh.pdfcreator.activity.PDFCreatorActivity$1.pdfGenerationFailure(PDFCreatorActivity.java:128)
            at com.tejpratapsingh.pdfcreator.utils.PDFUtil$GeneratePDFAsync.onPostExecute(PDFUtil.java:192)
            at com.tejpratapsingh.pdfcreator.utils.PDFUtil$GeneratePDFAsync.onPostExecute(PDFUtil.java:129)
    
    if(user.logoUrl != null){
        val uri = user.logoUrl!!.toUri()
        try {
                if(Build.VERSION.SDK_INT < 28) {
                    bitmap = MediaStore.Images.Media.getBitmap(
                        this.contentResolver,
                        uri
                    )
                } else {
                    val source = ImageDecoder.createSource(this.contentResolver, uri)
                    bitmap = ImageDecoder.decodeBitmap(source)
                }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        Log.i("Link", bitmap.toString())
        imageView.setImageBitmap(bitmap)
        imageLayoutParam.setMargins(0, 0, 10, 10)
        imageView.setLayout(imageLayoutParam)
        horizontalView.addView(imageView)
    }
    
    opened by madhall 4
  • How to add footer in all pages of pdf which is generate from html

    How to add footer in all pages of pdf which is generate from html

    Hello, please tell me is it possible to add footer all pages of pdf which is generate from html and page of pdf is changes dynamically according to data.

    wontfix 
    opened by vishalvala 4
  • Using '#' in PDFUtil.generatePDFFromHTML causes everything after the # to not print

    Using '#' in PDFUtil.generatePDFFromHTML causes everything after the # to not print

    For example: "The cat# in the hat" will show as "The cat". Is there a work around to this? Currently can't use Unicode because of this.

    opened by GrullonD 3
  • Display incorrect when pdf body is text only and the text is so long.

    Display incorrect when pdf body is text only and the text is so long.

    When pdf body is text only and the text is so long, then it create first blank page. The second page contains the text but it miss a lot of text, and the third page blank also.

    opened by antranvn 3
  • How can I customize the table

    How can I customize the table

    Hi @tejpratap46, How can I customize the table with my own style. I want to generate a PDF like different tables and some of the table consist of col-span and row-span. If any options available in the PDFTableView please inform. I did not find anything about the style properties of Table.

    opened by jerald-jacob 2
  • Loading Images from Mobile

    Loading Images from Mobile

    Hi Tej,

    The user is able to upload a default image using picasso, and the uri is stored. I tried the following approach to be able to display the image from the uri for the image stored in the phone gallery but it does not work... any suggestions please?

        val imageView = PDFImageView(applicationContext)
        val imageLayoutParam = LinearLayout.LayoutParams(
            60,
            60, 0F
        )
        if(user.logoUrl != null){
            val url = URL(user.logoUrl)
            val imageBmp = BitmapFactory.decodeStream(url.openConnection().getInputStream())
            imageView.setImageScale(ImageView.ScaleType.CENTER_INSIDE)
            imageView.setImageBitmap(imageBmp)
            // imageView.setImageResource(user!!.logoUrl)
            imageLayoutParam.setMargins(0, 0, 10, 10)
            imageView.setLayout(imageLayoutParam)
            horizontalView.addView(imageView)
        }
    

    thanks

    opened by madhall 2
  • generate pdf only after image has been retrieved from the web

    generate pdf only after image has been retrieved from the web

    I am including a logo that is saved online into the pdf. By the time the image is downloaded the pdf is generated and the image is not included - any suggestions?

    opened by madhall 1
  • Page size and color

    Page size and color

    Hi Tej,

    Anyway we can possibly add background colors to the page and change by section? Cant figure it out

    Also, where is the page size fixed, seems to be A4 need it to be custom.

    Thanks, Avinash

    enhancement 
    opened by madhall 1
  • Can we create a pdf by having fixed width and height may vary.

    Can we create a pdf by having fixed width and height may vary.

    I want to create a pdf from this library where i dont want to have more than one page, i want to have single scrollable page where i can print long receipt on a singlw roller print page . Can i achieve this using this library . thanks

    opened by wahdatjan 3
  • Arabic contents in PDFs generated from HTML

    Arabic contents in PDFs generated from HTML

    I am using the library in my android app since first release on March 2021. the generation from HTML with arabic contents was fine in first release. but when I published new release this month with new build, some devices running Android 11 especially OPPO phones (not all) fails to render arabic contents in the PDFs (it was working before but fails in the new release). I tried to embed fonts (attach the base64 string in the css) that support arabic in the HTML but with no luck.

    Could you please help.

    opened by muesmat 1
  • Pdf size issue

    Pdf size issue

    some devices creating the same content pdf in different sizes..some times get the file around 400kb and some times it more than 4MB...is there any solution for that ?

    bug 
    opened by afsalkodasseri 3
Releases(3.0.2)
Owner
Tej Pratap Singh
Build things to make life easier.
Tej Pratap Singh
View Inspection Toolbar for Android Development

View Inspector Plugin View inspection toolbar for android development. Features Boundary show outlines show margins show paddings Layer Scalpel featur

Fumihiro Xue (Peter Hsieh) 2.2k Nov 14, 2022
A simple utility to remove unused resources in your Android app to lower the size of the APK. It's based on the Android lint tool output.

android-resource-remover android-resource-remover is utility that removes unused resources reported by Android Lint from your project. The goal is to

Keepsafe 1.3k Dec 16, 2022
Annotation based simple API flavored with AOP to handle new Android runtime permission model

Let Annotation based simple API flavoured with AOP to handle new Android runtime permission model. If you check Google's Samples about the new permiss

Can Elmas 530 Nov 25, 2022
Simple Android SharedPreferences wrapper.

Prefs Simple Android SharedPreferences wrapper. Repository Add this in your root build.gradle file (not your module build.gradle file): allprojects {

null 130 Nov 11, 2022
Android Material Design Theme UI and Tool Library. Support: 4.0.3~O

GitHub OSChina 中文 English Genius-Android Genius-Android: by Material Design style and some commonly used packages. Starting in 2015, The divided into

Qiujuer 2.3k Dec 27, 2022
Android USB host serial driver library for CDC, FTDI, Arduino and other devices.

usb-serial-for-android This is a driver library for communication with Arduinos and other USB serial hardware on Android, using the Android USB Host M

mike w 3.8k Dec 30, 2022
Library that makes it possible to read, edit and write CSV files

AdaptiveTableLayout Welcome the new CSV Library AdaptiveTableLayout for Android by Cleveroad Pay your attention to our new library that makes it possi

Cleveroad 1.9k Jan 6, 2023
A library which will save you a lot of time from writing the same intent creation code. it consist of many intent creation codes like Share, Contacts, Email and etc, which you can easily use.

Android-Intent-Library A library which will save you a lot of time from writing the same intent creation code. it consist of many intent creation code

Next 67 Aug 24, 2022
Android Library Finder

alfi Android Library Finder Search through thousands of android libraries that can help you scale your projects elegantly Usage Search for something a

César Ferreira 509 Dec 8, 2022
Remote script to create a maven compatible release of an android library (aar)

release-android-library ?? Deprecated ?? This script is deprecated in favour of: novoda/bintray-release Remote script to create a maven compatible rel

Paul Blundell 144 Dec 13, 2022
:inbox_tray: [Android Library] Hunt down all package information

Android library to hunt down package information. The library is built for simplicity and approachability. It not only eliminates most boilerplate cod

Nishant Srivastava 141 Nov 17, 2022
An android library that handles the closing of your app interactively.

Shutdown A library that handles the closing of your app interactively. Overview of Shutdown library Shutdown library handles the closing of your app i

Emmanuel Kehinde 56 Oct 5, 2022
TaggerString is very light library which allows to build dynamic string resource in much more readable way.

TaggerString TaggerString is very light library which allows to build dynamic string resource in much more readable way. I guess that every Android de

polok 241 Jun 3, 2022
The Kotlin fake data generator library!

Fakeit This library is a port of the Ruby gem Faker. It generates realistic fake data — like names, emails, dates, countries — for a variety of scenar

Moove It 517 Nov 20, 2022
Android Resource Manager application to manage and analysis your app resources with many features like image resize, Color, Dimens and code Analysis

Android Resource Manager application to manage and analysis your app resources with many features like image resize, Color, Dimens and code Analysis

Amr Hesham 26 Nov 16, 2022
A tool to install components of the Android SDK into a Maven repository or repository manager to use with the Android Maven Plugin, Gradle and other tools.

Maven Android SDK Deployer Original author including numerous fixes and changes: Manfred Moser [email protected] at simpligility technologies i

simpligility 1.4k Dec 27, 2022