├── .gitignore
├── .idea
├── codeStyles
│ └── Project.xml
├── compiler.xml
├── gradle.xml
├── jarRepositories.xml
├── misc.xml
└── vcs.xml
├── LICENSE
├── README.md
├── build.gradle
├── demo-home-screen-ss.png
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── jitpack.yml
├── logo.png
├── sample
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── emon
│ │ └── exampleXMLtoPDF
│ │ └── ExampleInstrumentedTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── emon
│ │ │ └── exampleXMLtoPDF
│ │ │ ├── MainActivity.java
│ │ │ ├── demoInvoice
│ │ │ └── DemoInvoiceFragment.java
│ │ │ └── dummyList
│ │ │ ├── DummyContent.java
│ │ │ └── DummyItemRecyclerViewAdapter.java
│ └── res
│ │ ├── drawable-v24
│ │ └── ic_launcher_foreground.xml
│ │ ├── drawable
│ │ └── ic_launcher_background.xml
│ │ ├── layout
│ │ ├── activity_main.xml
│ │ ├── demo_a4_sized_page.xml
│ │ ├── demo_barcode.xml
│ │ ├── demo_barcode_90_degree_rotated.xml
│ │ ├── fragment_demo_invoice.xml
│ │ ├── fragment_item.xml
│ │ ├── item_boxes.xml
│ │ ├── layout_print.xml
│ │ ├── layout_print_horizontal_scroll.xml
│ │ ├── layout_test_invoice.xml
│ │ └── rv_item_list.xml
│ │ ├── mipmap-anydpi-v26
│ │ ├── ic_launcher.xml
│ │ └── ic_launcher_round.xml
│ │ ├── mipmap-hdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-mdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ └── values
│ │ ├── colors.xml
│ │ ├── dimens.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test
│ └── java
│ └── com
│ └── emon
│ └── exampleXMLtoPDF
│ └── ExampleUnitTest.java
├── settings.gradle
└── xml-to-pdf
├── .gitignore
├── build.gradle
├── consumer-rules.pro
├── proguard-rules.pro
└── src
├── androidTest
└── java
│ └── com
│ └── gkemon
│ └── XMLtoPDF
│ └── ExampleInstrumentedTest.java
├── main
├── AndroidManifest.xml
├── java
│ └── com
│ │ └── gkemon
│ │ └── XMLtoPDF
│ │ ├── FileUtils.java
│ │ ├── PdfGenerator.java
│ │ ├── PdfGeneratorListener.java
│ │ ├── Utils.java
│ │ └── model
│ │ ├── FailureResponse.java
│ │ ├── SuccessResponse.java
│ │ └── XmlToPDFFileProvider.java
└── res
│ ├── values
│ └── strings.xml
│ └── xml
│ └── provider_paths.xml
└── test
└── java
└── com
└── gkemon
└── XMLtoPDF
└── ExampleUnitTest.java
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/caches
5 | /.idea/libraries
6 | /.idea/modules.xml
7 | /.idea/workspace.xml
8 | /.idea/navEditor.xml
9 | /.idea/assetWizardSettings.xml
10 | .DS_Store
11 | /build
12 | /captures
13 | .externalNativeBuild
14 | .cxx
15 |
--------------------------------------------------------------------------------
/.idea/codeStyles/Project.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 | xmlns:android
32 |
33 | ^$
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 | xmlns:.*
43 |
44 | ^$
45 |
46 |
47 | BY_NAME
48 |
49 |
50 |
51 |
52 |
53 |
54 | .*:id
55 |
56 | http://schemas.android.com/apk/res/android
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 | .*:name
66 |
67 | http://schemas.android.com/apk/res/android
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 | name
77 |
78 | ^$
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 | style
88 |
89 | ^$
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 | .*
99 |
100 | ^$
101 |
102 |
103 | BY_NAME
104 |
105 |
106 |
107 |
108 |
109 |
110 | .*
111 |
112 | http://schemas.android.com/apk/res/android
113 |
114 |
115 | ANDROID_ATTRIBUTE_ORDER
116 |
117 |
118 |
119 |
120 |
121 |
122 | .*
123 |
124 | .*
125 |
126 |
127 | BY_NAME
128 |
129 |
130 |
131 |
132 |
133 |
134 |
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/.idea/jarRepositories.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | XML to PDF Generator For Android
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 | Automatically generate PDF file from XML file or Java's View object in Android
16 |
Make PDF from Android layout resources (e.g - R.layout.myLayout,R.id.viewID) ids or directly views objects
17 |
18 | Run the sample app and see it's or youtube video below for getting more clearance.
19 |
20 |
21 |
22 |
23 |
24 | * **Simple**: Extremely simple to use. For using Step Builder Design Patten undernath,here IDE greatly helps developers to complete the steps for creating a PDF from XMLs.
25 | * **Powerful**: Customize almost everything.
26 | * **Transparent**: It shows logs,success-responses, failure-responses , that's why developer will nofity any event inside the process.
27 |
28 |
29 | 📖 Table of Contents
30 |
31 |
32 | [](#table-of-contents)
33 |
34 | ## ➤ Table of Contents
35 |
36 | * [➤ Installation](#-installation)
37 | * [➤ Getting Started](#-getting-started)
38 | * [➤ License](#-license)
39 |
40 |
41 |
42 | [](#installation)
43 |
44 | ## ➤ Installation
45 |
46 | **Step 1**. Add the JitPack repository to your root ```build.gradle``` at the end of repositories
47 | ```
48 | android {
49 | .
50 | .
51 |
52 | /*Need Java version 1.8 as Rx java is used for file write underneath for preventing UI freezing*/
53 | compileOptions {
54 | sourceCompatibility JavaVersion.VERSION_1_8
55 | targetCompatibility JavaVersion.VERSION_1_8
56 | }
57 | .
58 | .
59 | }
60 | .
61 | .
62 | allprojects {
63 | repositories {
64 | // ...
65 | maven { url 'https://jitpack.io' }
66 | }
67 | }
68 | .
69 | .
70 | ```
71 |
72 | **Step 2**. Add the dependency
73 | ```
74 | dependencies {
75 | implementation 'com.github.Gkemon:Android-XML-to-PDF-Generator:2.6.8'
76 | }
77 | ```
78 | [](#getting-started-quick)
79 |
80 |
81 |
82 | ## ➤ Getting Started
83 |
84 | You can generate PDF from many sources.
85 | * Layout resources (i.e: ```R.layout.myLayout```)
86 | * View ids (i.e: ```R.id.viewID```)
87 | * Java view objects (i.e ```View```,```TextView```,```LinearLayout```) because sometimes we need to change the content of the XML and then dealing this java view object is only way to do this.
88 |
89 | ## ➤ Important Note
90 | 
91 | 
92 | 
93 | For better output and make the PDF more responsive,please try to set ```android:layout_width``` of the top most view of XML a fixed value in pixel or ```px``` (Recommandation is not use ```dp``` as it depends on device screen) instead of ```wrap_content``` and ```match_parent``` otherwise sizing could be malformed in PDF for different device screen.Suppose if you want to print an A4 sized pdf so you can see my example from [where](https://github.com/Gkemon/Android-XML-to-PDF-Generator/blob/master/sample/src/main/res/layout/demo_a4_sized_page.xml). You just need to make your XML's width:hight aspected ratio 1:1.14142. Referece is [here](https://www.papersizes.org/sp/a/a4#:~:text=The%20aspect%20ratio%20(width%3Aheight,(1%3A%E2%88%9A2) ).
94 | 
95 | 
96 | 
97 |
98 | ### From layout resources :
99 | ( Only static content in XML will be printed by this approach. If you want to change the content of the XML ,suppose there is a
100 | text view in the XML and you want to populate it with a data then try the [approach](https://github.com/Gkemon/Android-XML-to-PDF-Generator/edit/master/README.md#from-views) )
101 |
102 |
103 | ```java
104 | PdfGenerator.getBuilder()
105 | .setContext(context)
106 | .fromLayoutXMLSource()
107 | .fromLayoutXML(R.layout.layout_print,R.layout.layout_print)
108 | /* "fromLayoutXML()" takes array of layout resources.
109 | * You can also invoke "fromLayoutXMLList()" method here which takes list of layout resources instead of array. */
110 | .setFileName("Test-PDF")
111 | /* It is file name */
112 | .setFolderName("FolderA/FolderB/FolderC")
113 | /* It is folder name. If you set the folder name like this pattern (FolderA/FolderB/FolderC), then
114 | * FolderA creates first.Then FolderB inside FolderB and also FolderC inside the FolderB and finally
115 | * the pdf file named "Test-PDF.pdf" will be store inside the FolderB. */
116 | .actionAfterPDFGeneration(PdfGenerator.ActionAfterPDFGeneration.SHARE)
117 | /*If you want to save your pdf in shared storage (where other apps can also see your pdf even after the app is uninstall).
118 | * You need to pass an xmt to pdf lifecycle observer by the following method. To get complete overview please see the MainActivity of 'sample' folder */
119 | .savePDFSharedStorage(xmlToPDFLifecycleObserver)
120 | /* It true then the generated pdf will be shown after generated. */
121 | .build(new PdfGeneratorListener() {
122 | @Override
123 | public void onFailure(FailureResponse failureResponse) {
124 | super.onFailure(failureResponse);
125 | /* If pdf is not generated by an error then you will findout the reason behind it
126 | * from this FailureResponse. */
127 | }
128 | @Override
129 | public void onStartPDFGeneration() {
130 | /*When PDF generation begins to start*/
131 | }
132 |
133 | @Override
134 | public void onFinishPDFGeneration() {
135 | /*When PDF generation is finished*/
136 | }
137 |
138 | @Override
139 | public void showLog(String log) {
140 | super.showLog(log);
141 | /*It shows logs of events inside the pdf generation process*/
142 | }
143 |
144 | @Override
145 | public void onSuccess(SuccessResponse response) {
146 | super.onSuccess(response);
147 | /* If PDF is generated successfully then you will find SuccessResponse
148 | * which holds the PdfDocument,File and path (where generated pdf is stored)*/
149 |
150 | }
151 | });
152 | ```
153 |
154 | ### From view IDs :
155 |
156 | ```java
157 | PdfGenerator.getBuilder()
158 | .setContext(context)
159 | .fromViewIDSource()
160 | .fromViewID(R.layout.hostLayout,activity,R.id.tv_print_area,R.id.tv_print_area)
161 | /* "fromViewID()" takes array of view ids and the host layout xml where the view ids are belonging.
162 | * You can also invoke "fromViewIDList()" method here which takes list of view ids instead of array.*/
163 | .setFileName("Test-PDF")
164 | .setFolderName("Test-PDF-folder")
165 | .actionAfterPDFGeneration(PdfGenerator.ActionAfterPDFGeneration.OPEN)
166 | .build(new PdfGeneratorListener() {
167 | @Override
168 | public void onFailure(FailureResponse failureResponse) {
169 | super.onFailure(failureResponse);
170 | }
171 |
172 | @Override
173 | public void onStartPDFGeneration() {
174 | /*When PDF generation begins to start*/
175 | }
176 |
177 | @Override
178 | public void onFinishPDFGeneration() {
179 | /*When PDF generation is finished*/
180 | }
181 |
182 | @Override
183 | public void showLog(String log) {
184 | super.showLog(log);
185 | }
186 |
187 | @Override
188 | public void onSuccess(SuccessResponse response) {
189 | super.onSuccess(response);
190 | }
191 | });
192 | ```
193 |
194 | ### From views:
195 | ( This approach is perfect when you need to change the XML content. You can change the content getting them by ```findViewById``` and change them and finally print them. Other example is [here](https://github.com/Gkemon/Android-XML-to-PDF-Generator/issues/4#issuecomment-712690701) )
196 | ```java
197 |
198 |
199 | TextView tvText = view.findViewByID(R.id.tv_text_1);
200 | tvText.setText("My changed content");
201 | //By the following statements, we are changing the text view inside of our target "view" which is going to be changed.
202 | //So if we now print the "view" then you will see the changed text in the pdf.
203 |
204 | PdfGenerator.getBuilder()
205 | .setContext(MainActivity.this)
206 | .fromViewSource()
207 | .fromView(view)
208 | .setFileName("Test-PDF")
209 | .setFolderName("Test-PDF-folder")
210 | .actionAfterPDFGeneration(PdfGenerator.ActionAfterPDFGeneration.OPEN)
211 | .build(new PdfGeneratorListener() {
212 | @Override
213 | public void onFailure(FailureResponse failureResponse) {
214 | super.onFailure(failureResponse);
215 | }
216 |
217 | @Override
218 | public void showLog(String log) {
219 | super.showLog(log);
220 | }
221 |
222 | @Override
223 | public void onStartPDFGeneration() {
224 | /*When PDF generation begins to start*/
225 | }
226 |
227 | @Override
228 | public void onFinishPDFGeneration() {
229 | /*When PDF generation is finished*/
230 | }
231 |
232 | @Override
233 | public void onSuccess(SuccessResponse response) {
234 | super.onSuccess(response);
235 | }
236 | });
237 | ```
238 |
239 | ### Multi-paged PDF creation:
240 | Users of the library, sometimes have doubts that how to create multi-paged PDF. Though I mentioned it above but I need to show it again for more clearance.
241 | You can insert multiple xml or views object even view id in the parameter of the following methods to create multi-paged pdf:
242 |
243 |
244 | If you want create multi-paged pdf from xmls-
245 |
246 | `.fromLayoutXML(R.layout.layout_1,R.layout.layout_2)`
247 |
248 | If you want create multi-paged pdf from view ids -
249 |
250 | `.fromViewID(activity,R.id.viewId1,R.id.viewId2)`
251 |
252 | If you want create multi-paged pdf from views-
253 |
254 | `.fromViewID(view1,view1)`
255 |
256 | ### How to print an Invoice Or Report ?
257 | Sometimes people gets stuck to print invoice or report via this library.So I wrote an example invoice/report printing fragment to visualise how to print an Invoice or Report . Here is [the link also with an important documentation](https://github.com/Gkemon/Android-XML-to-PDF-Generator/blob/master/sample/src/main/java/com/emon/exampleXMLtoPDF/demoInvoice/DemoInvoiceFragment.java)
258 |
259 |
260 | ### How to deal with generated PDF?
261 | With a method calling named `openPDFafterGeneration(true)`, the generated file will be automatically opened automatically.So you DON'T NEED TO BE BOTHER FOR IT . [FileProvider](https://developer.android.com/reference/androidx/core/content/FileProvider) is used to open file here. To get a good insight about it please see the [tutorial](https://vladsonkin.com/how-to-share-files-with-android-fileprovider/). The `android:authorities` name in the app is `${applicationId}.xmlToPdf.provider` which might be needed if you want to deal with generated file CUSTOMLY ,not letting the app open the generated file. you will get the generated file path in `onSuccess(SuccessResponse response)` response.
262 |
263 | ### Troubleshoot
264 | * Try to avoid to provide `match_parent` and `wrap_content` height/width in XML. So it specifically.
265 | * If any of your footer view is not placed the footer position then you need adjust it using `marginTop` and keep it in a `ScrollView`.For example this [issue](https://github.com/Gkemon/Android-XML-to-PDF-Generator/issues/16) is fixed by rearranging XML like [this](https://github.com/Gkemon/Android-XML-to-PDF-Generator/blob/master/sample/src/main/res/layout/layout_test_invoice.xml)
266 |
267 | So if you find any trouble,then you are also welcomed again to knock me.Thank you so much.
268 |
269 |
270 | [](#templates)
271 |
272 |
273 |
274 | LinkedIn
275 |
276 |
277 | Inbox
278 |
279 |
280 |
281 | #### Logo credit: [kirillmazin](https://www.behance.net/kirillmazin)
282 |
283 | ## ➤ License
284 |
285 | The source code is licensed under the [Apache License 2.0](https://github.com/Gkemon/XML-to-PDF-generator/blob/master/LICENSE).
286 |
287 |
288 | [](#license)
289 |
290 |
291 | ## ➤ App using it
292 | * [Codeddit Programmer Community](
293 | https://play.google.com/store/apps/details?id=com.codedditapp.codeddit)
294 | * [হাজিরা খাতা - Attendance sheet - HaziraKhata](
295 | https://play.google.com/store/apps/details?id=com.Teachers.HaziraKhataByGk)
296 | * [Trust Axiata Pay](
297 | https://play.google.com/store/apps/details?id=com.tad.bdkepler&hl=en&gl=US)
298 | * [Prideboard](https://play.google.com/store/apps/details?id=com.pridesys.prideboard)
299 |
300 | * [Treatbook - Your Health Coach and Medical Tracker](
301 | https://play.google.com/store/apps/details?id=com.newlit.treatbook&hl=en&gl=US)
302 |
303 | * [Mobflow](
304 | https://play.google.com/store/apps/details?id=com.brazzo.mobflow)
305 |
306 | * [Front Benchers](https://play.google.com/store/apps/details?id=com.mr_17.front_benchers)
307 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | google()
6 | jcenter()
7 |
8 | }
9 | dependencies {
10 | classpath 'com.android.tools.build:gradle:7.4.2'
11 |
12 | // NOTE: Do not place your application dependencies here; they belong
13 | // in the individual module build.gradle files
14 | }
15 | }
16 |
17 | allprojects {
18 | repositories {
19 | google()
20 | jcenter()
21 | maven { url 'https://jitpack.io' }
22 | }
23 | }
24 |
25 | task clean(type: Delete) {
26 | delete rootProject.buildDir
27 | }
28 |
--------------------------------------------------------------------------------
/demo-home-screen-ss.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gkemon/Android-XML-to-PDF-Generator/033719775de5b3336f8308beca601dbc365a21fe/demo-home-screen-ss.png
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx1536m
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app's APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 |
19 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gkemon/Android-XML-to-PDF-Generator/033719775de5b3336f8308beca601dbc365a21fe/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Sat Feb 13 15:47:55 BDT 2021
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-bin.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/jitpack.yml:
--------------------------------------------------------------------------------
1 | jdk:
2 | - openjdk11
3 | before_install:
4 | - sdk install java 11.0.10-open
5 | - sdk use java 11.0.10-open
--------------------------------------------------------------------------------
/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gkemon/Android-XML-to-PDF-Generator/033719775de5b3336f8308beca601dbc365a21fe/logo.png
--------------------------------------------------------------------------------
/sample/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/sample/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 33
5 | defaultConfig {
6 | applicationId "com.emon.XMLtoPDF"
7 | minSdkVersion 21
8 | targetSdkVersion 33
9 | versionCode 1
10 | versionName "1.0"
11 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
12 | }
13 | buildTypes {
14 | release {
15 | minifyEnabled false
16 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
17 | }
18 | }
19 | compileOptions {
20 | sourceCompatibility JavaVersion.VERSION_11
21 | targetCompatibility JavaVersion.VERSION_11
22 | }
23 | namespace 'com.emon.exampleXMLtoPDF'
24 | }
25 |
26 | dependencies {
27 | implementation fileTree(dir: 'libs', include: ['*.jar'])
28 | implementation 'androidx.appcompat:appcompat:1.5.1'
29 | implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
30 | implementation 'androidx.legacy:legacy-support-v4:1.0.0'
31 | testImplementation 'junit:junit:4.13.2'
32 | androidTestImplementation 'androidx.test:runner:1.5.1'
33 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.0'
34 | implementation 'com.intuit.ssp:ssp-android:1.1.0'
35 | implementation 'com.intuit.sdp:sdp-android:1.1.0'
36 | implementation 'androidx.recyclerview:recyclerview:1.2.1'
37 | implementation 'com.github.bumptech.glide:glide:4.14.1'
38 | annotationProcessor 'com.github.bumptech.glide:compiler:4.14.1'
39 | /*Comment out the line below if you want to use library locally*/
40 | implementation project(path: ':xml-to-pdf')
41 |
42 | /*Comment out the line below if you want to use library from jitpack repo*/
43 | //implementation 'com.github.Gkemon:Android-XML-to-PDF-Generator:2.6.7'
44 | }
45 |
--------------------------------------------------------------------------------
/sample/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/sample/src/androidTest/java/com/emon/exampleXMLtoPDF/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.emon.exampleXMLtoPDF;
2 |
3 | import android.content.Context;
4 |
5 | import androidx.test.platform.app.InstrumentationRegistry;
6 | import androidx.test.runner.AndroidJUnit4;
7 |
8 | import org.junit.Test;
9 | import org.junit.runner.RunWith;
10 |
11 | import static org.junit.Assert.*;
12 |
13 | /**
14 | * Instrumented test, which will execute on an Android device.
15 | *
16 | * @see Testing documentation
17 | */
18 | @RunWith(AndroidJUnit4.class)
19 | public class ExampleInstrumentedTest {
20 | @Test
21 | public void useAppContext() {
22 | // Context of the app under test.
23 | Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
24 |
25 | assertEquals("com.emon.XMLtoPDF", appContext.getPackageName());
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/sample/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
13 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/emon/exampleXMLtoPDF/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.emon.exampleXMLtoPDF;
2 |
3 | import android.content.Context;
4 | import android.os.Bundle;
5 | import android.util.Log;
6 | import android.view.LayoutInflater;
7 | import android.view.View;
8 | import android.widget.Button;
9 | import android.widget.EditText;
10 | import android.widget.TextView;
11 | import android.widget.Toast;
12 |
13 | import androidx.appcompat.app.AlertDialog;
14 | import androidx.appcompat.app.AppCompatActivity;
15 | import androidx.fragment.app.Fragment;
16 | import androidx.recyclerview.widget.LinearLayoutManager;
17 | import androidx.recyclerview.widget.RecyclerView;
18 |
19 | import com.emon.exampleXMLtoPDF.demoInvoice.DemoInvoiceFragment;
20 | import com.emon.exampleXMLtoPDF.dummyList.DummyContent;
21 | import com.emon.exampleXMLtoPDF.dummyList.DummyItemRecyclerViewAdapter;
22 | import com.gkemon.XMLtoPDF.PdfGenerator;
23 | import com.gkemon.XMLtoPDF.PdfGeneratorListener;
24 | import com.gkemon.XMLtoPDF.model.FailureResponse;
25 | import com.gkemon.XMLtoPDF.model.SuccessResponse;
26 |
27 | public class MainActivity extends AppCompatActivity {
28 | Button btnPrint, btnPrintMultiPage, btnInvoice, btnDemoBarcode, btnPrintDemoList,
29 | btnPrintMultiPageDynamic, btnPrintHorizontalScrollView, btnPrintLandscape;
30 | private Fragment demoInvoiceFragment;
31 | private PdfGenerator.XmlToPDFLifecycleObserver xmlToPDFLifecycleObserver;
32 |
33 | @Override
34 | protected void onCreate(Bundle savedInstanceState) {
35 | super.onCreate(savedInstanceState);
36 | setContentView(R.layout.activity_main);
37 | btnPrint = findViewById(R.id.bt_print);
38 | btnPrintMultiPage = findViewById(R.id.bt_print_multi_page);
39 | btnInvoice = findViewById(R.id.bt_invoice);
40 | btnDemoBarcode = findViewById(R.id.bt_demo_barcode);
41 | btnPrintDemoList = findViewById(R.id.bt_print_list);
42 | btnPrintMultiPageDynamic = findViewById(R.id.bt_print_multi_page_dynamic);
43 | btnPrintHorizontalScrollView = findViewById(R.id.bt_horizontal_scroll_view);
44 | btnPrintLandscape = findViewById(R.id.bt_print_landscape);
45 | demoInvoiceFragment = new DemoInvoiceFragment();
46 |
47 | xmlToPDFLifecycleObserver = new PdfGenerator.XmlToPDFLifecycleObserver(this);
48 | getLifecycle().addObserver(xmlToPDFLifecycleObserver);
49 |
50 |
51 | btnPrint.setOnClickListener(new View.OnClickListener() {
52 | @Override
53 | public void onClick(View v) {
54 |
55 | /**
56 | * MUST NEED TO set android:layout_width A FIXED
57 | * VALUE INSTEAD OF "wrap_content" and "match_parent" OTHERWISE SIZING COULD BE MALFORMED
58 | * IN PDF FOR DIFFERENT DEVICE SCREEN
59 | */
60 |
61 | PdfGenerator.getBuilder()
62 | .setContext(MainActivity.this)
63 | .fromViewIDSource()
64 | .fromViewID(MainActivity.this, R.id.tv_print_area)
65 | .setFileName("Demo-Text")
66 | .actionAfterPDFGeneration(PdfGenerator.ActionAfterPDFGeneration.SHARE)
67 | .savePDFSharedStorage(xmlToPDFLifecycleObserver)
68 | .build(new PdfGeneratorListener() {
69 | @Override
70 | public void onFailure(FailureResponse failureResponse) {
71 | super.onFailure(failureResponse);
72 | }
73 |
74 | @Override
75 | public void onStartPDFGeneration() {
76 |
77 | }
78 |
79 | @Override
80 | public void onFinishPDFGeneration() {
81 |
82 | }
83 |
84 | @Override
85 | public void showLog(String log) {
86 | super.showLog(log);
87 | Log.d("PDF-generation",log);
88 | }
89 |
90 | @Override
91 | public void onSuccess(SuccessResponse response) {
92 | super.onSuccess(response);
93 | }
94 | });
95 | }
96 | });
97 |
98 | btnPrintHorizontalScrollView.setOnClickListener(new View.OnClickListener() {
99 | @Override
100 | public void onClick(View v) {
101 |
102 | /**
103 | * MUST NEED TO set android:layout_width A FIXED
104 | * VALUE INSTEAD OF "wrap_content" and "match_parent" OTHERWISE SIZING COULD BE MALFORMED
105 | * IN PDF FOR DIFFERENT DEVICE SCREEN
106 | */
107 |
108 | PdfGenerator.getBuilder()
109 | .setContext(MainActivity.this)
110 | .fromLayoutXMLSource()
111 | .fromLayoutXML(R.layout.layout_print_horizontal_scroll)
112 | .setFileName("Demo-Horizontal-Scroll-View-Text")
113 | .setFolderNameOrPath("MyFolder/MyDemoHorizontalText/")
114 | .actionAfterPDFGeneration(PdfGenerator.ActionAfterPDFGeneration.NONE)
115 | .build(new PdfGeneratorListener() {
116 | @Override
117 | public void onFailure(FailureResponse failureResponse) {
118 | super.onFailure(failureResponse);
119 | }
120 |
121 | @Override
122 | public void onStartPDFGeneration() {
123 |
124 | }
125 |
126 | @Override
127 | public void onFinishPDFGeneration() {
128 |
129 | }
130 |
131 | @Override
132 | public void showLog(String log) {
133 | super.showLog(log);
134 | }
135 |
136 | @Override
137 | public void onSuccess(SuccessResponse response) {
138 | super.onSuccess(response);
139 | Toast.makeText(MainActivity.this,"Generation is done",Toast.LENGTH_LONG).show();
140 | }
141 | });
142 | }
143 | });
144 |
145 | btnPrintLandscape.setOnClickListener(new View.OnClickListener() {
146 | @Override
147 | public void onClick(View v) {
148 |
149 | /**
150 | * MUST NEED TO set android:layout_width A FIXED
151 | * VALUE INSTEAD OF "wrap_content" and "match_parent" OTHERWISE SIZING COULD BE MALFORMED
152 | * IN PDF FOR DIFFERENT DEVICE SCREEN
153 | */
154 |
155 | PdfGenerator.getBuilder()
156 | .setContext(MainActivity.this)
157 | .fromViewIDSource()
158 | .fromViewID(MainActivity.this, R.id.tv_print_area)
159 | .setFileName("Demo-Landscape")
160 | .setFolderNameOrPath("MyFolder/MyDemoLandscape/")
161 | .actionAfterPDFGeneration(PdfGenerator.ActionAfterPDFGeneration.SHARE)
162 | .build(new PdfGeneratorListener() {
163 | @Override
164 | public void onFailure(FailureResponse failureResponse) {
165 | super.onFailure(failureResponse);
166 | }
167 |
168 | @Override
169 | public void onStartPDFGeneration() {
170 |
171 | }
172 |
173 | @Override
174 | public void onFinishPDFGeneration() {
175 |
176 | }
177 |
178 | @Override
179 | public void showLog(String log) {
180 | super.showLog(log);
181 | }
182 |
183 | @Override
184 | public void onSuccess(SuccessResponse response) {
185 | super.onSuccess(response);
186 | }
187 | });
188 | }
189 | });
190 |
191 |
192 | btnPrintMultiPage.setOnClickListener(new View.OnClickListener() {
193 | @Override
194 | public void onClick(View v) {
195 |
196 | /**
197 | * MUST NEED TO set android:layout_width A FIXED
198 | * VALUE INSTEAD OF "wrap_content" and "match_parent" OTHERWISE SIZING COULD BE MALFORMED
199 | * IN PDF FOR DIFFERENT DEVICE SCREEN
200 | */
201 |
202 | PdfGenerator.getBuilder()
203 | .setContext(MainActivity.this)
204 | .fromViewIDSource()
205 | .fromViewID(MainActivity.this,
206 | R.id.tv_print_area, R.id.tv_print_area, R.id.tv_print_area)
207 | .setFileName("Demo-Text-Multi-Page")
208 | .setFolderNameOrPath("MyFolder/MyDemoTextMultiPage/")
209 | .savePDFSharedStorage(xmlToPDFLifecycleObserver)
210 | .actionAfterPDFGeneration(PdfGenerator.ActionAfterPDFGeneration.OPEN)
211 | .build(new PdfGeneratorListener() {
212 | @Override
213 | public void onFailure(FailureResponse failureResponse) {
214 | super.onFailure(failureResponse);
215 | }
216 |
217 | @Override
218 | public void onStartPDFGeneration() {
219 |
220 | }
221 |
222 | @Override
223 | public void onFinishPDFGeneration() {
224 |
225 | }
226 |
227 | @Override
228 | public void showLog(String log) {
229 | super.showLog(log);
230 | }
231 |
232 | @Override
233 | public void onSuccess(SuccessResponse response) {
234 | super.onSuccess(response);
235 | }
236 | });
237 | }
238 | });
239 | btnPrintMultiPageDynamic.setOnClickListener(new View.OnClickListener() {
240 | @Override
241 | public void onClick(View v) {
242 | final EditText editText = new EditText(v.getContext());
243 |
244 | new AlertDialog.Builder(v.getContext())
245 | .setTitle("Input dynamic text")
246 | .setMessage("Please input your demo text. It will populate a multi " +
247 | "paged pdf with your demo text")
248 | .setView(editText)
249 | .setPositiveButton("Input", (dialog, whichButton) -> {
250 | LayoutInflater inflater = (LayoutInflater)
251 | getSystemService(Context.LAYOUT_INFLATER_SERVICE);
252 |
253 | /**
254 | * MUST NEED TO set android:layout_width A FIXED
255 | * VALUE INSTEAD OF "wrap_content" and "match_parent" OTHERWISE SIZING COULD BE MALFORMED
256 | * IN PDF FOR DIFFERENT DEVICE SCREEN
257 | */
258 | View content = inflater.inflate(R.layout.activity_main, null);
259 | TextView tvDynamicText = content.findViewById(R.id.tv_print_area);
260 | tvDynamicText.setText(editText.getText().toString());
261 |
262 | PdfGenerator.getBuilder()
263 | .setContext(MainActivity.this)
264 | .fromViewSource()
265 | .fromView(tvDynamicText, tvDynamicText, tvDynamicText)
266 | .setFileName("Demo-Text-Multi-Page-With-Dynamic-Text")
267 | .actionAfterPDFGeneration(PdfGenerator.ActionAfterPDFGeneration.SHARE)
268 | .build(new PdfGeneratorListener() {
269 | @Override
270 | public void onFailure(FailureResponse failureResponse) {
271 | super.onFailure(failureResponse);
272 | }
273 |
274 | @Override
275 | public void onStartPDFGeneration() {
276 |
277 | }
278 |
279 | @Override
280 | public void onFinishPDFGeneration() {
281 |
282 | }
283 |
284 | @Override
285 | public void showLog(String log) {
286 | super.showLog(log);
287 | }
288 |
289 | @Override
290 | public void onSuccess(SuccessResponse response) {
291 | super.onSuccess(response);
292 | }
293 | });
294 | })
295 | .setNegativeButton("Cancel", (dialog, whichButton) -> {
296 | dialog.dismiss();
297 | })
298 | .show();
299 |
300 | }
301 | });
302 |
303 |
304 | btnDemoBarcode.setOnClickListener(new View.OnClickListener() {
305 | @Override
306 | public void onClick(View v) {
307 | LayoutInflater inflater = (LayoutInflater)
308 | getSystemService(Context.LAYOUT_INFLATER_SERVICE);
309 | /**
310 | * MUST NEED TO set android:layout_width A FIXED
311 | * VALUE INSTEAD OF "wrap_content" and "match_parent" OTHERWISE SIZING COULD BE MALFORMED
312 | * IN PDF FOR DIFFERENT DEVICE SCREEN
313 | */
314 | View content = inflater.inflate(R.layout.demo_barcode, null);
315 | PdfGenerator.getBuilder()
316 | .setContext(MainActivity.this)
317 | .fromViewSource()
318 | .fromView(content, content, content)
319 | .setFileName("Demo-Barcode")
320 | .actionAfterPDFGeneration(PdfGenerator.ActionAfterPDFGeneration.OPEN)
321 | .build(new PdfGeneratorListener() {
322 | @Override
323 | public void onFailure(FailureResponse failureResponse) {
324 | super.onFailure(failureResponse);
325 | }
326 |
327 | @Override
328 | public void onStartPDFGeneration() {
329 |
330 | }
331 |
332 | @Override
333 | public void onFinishPDFGeneration() {
334 |
335 | }
336 |
337 | @Override
338 | public void showLog(String log) {
339 | super.showLog(log);
340 | }
341 |
342 | @Override
343 | public void onSuccess(SuccessResponse response) {
344 | super.onSuccess(response);
345 | }
346 | });
347 | }
348 | });
349 |
350 | btnPrintDemoList.setOnClickListener(new View.OnClickListener() {
351 | @Override
352 | public void onClick(View v) {
353 |
354 | LayoutInflater inflater = (LayoutInflater)
355 | getSystemService(Context.LAYOUT_INFLATER_SERVICE);
356 |
357 | View content = inflater.inflate(R.layout.rv_item_list, null);
358 |
359 | RecyclerView recyclerView = content.findViewById(R.id.list);
360 | recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
361 | recyclerView.setAdapter(new DummyItemRecyclerViewAdapter(DummyContent.ITEMS));
362 |
363 | PdfGenerator.getBuilder()
364 | .setContext(MainActivity.this)
365 | .fromViewSource()
366 | .fromView(content)
367 | .setFileName("Demo-List")
368 | .setFolderNameOrPath("MyFolder/MyDemoList/")
369 | .actionAfterPDFGeneration(PdfGenerator.ActionAfterPDFGeneration.OPEN)
370 | .build(new PdfGeneratorListener() {
371 | @Override
372 | public void onFailure(FailureResponse failureResponse) {
373 | super.onFailure(failureResponse);
374 | }
375 |
376 | @Override
377 | public void onStartPDFGeneration() {
378 |
379 | }
380 |
381 | @Override
382 | public void onFinishPDFGeneration() {
383 |
384 | }
385 |
386 | @Override
387 | public void showLog(String log) {
388 | super.showLog(log);
389 | }
390 |
391 | @Override
392 | public void onSuccess(SuccessResponse response) {
393 | super.onSuccess(response);
394 | }
395 | });
396 |
397 | }
398 | });
399 |
400 | btnInvoice.setOnClickListener(v -> {
401 | if (getSupportFragmentManager().findFragmentById(android.R.id.content) == null) {
402 | getSupportFragmentManager().beginTransaction()
403 | .add(android.R.id.content, demoInvoiceFragment)
404 | .commit();
405 | }
406 | });
407 |
408 | }
409 |
410 | @Override
411 | public void onBackPressed() {
412 | getSupportFragmentManager().beginTransaction().remove(demoInvoiceFragment).commit();
413 | }
414 |
415 | }
416 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/emon/exampleXMLtoPDF/demoInvoice/DemoInvoiceFragment.java:
--------------------------------------------------------------------------------
1 | package com.emon.exampleXMLtoPDF.demoInvoice;
2 |
3 | import android.os.Bundle;
4 |
5 | import androidx.fragment.app.Fragment;
6 | import androidx.recyclerview.widget.LinearLayoutManager;
7 | import androidx.recyclerview.widget.RecyclerView;
8 |
9 | import android.text.Html;
10 | import android.util.Log;
11 | import android.view.LayoutInflater;
12 | import android.view.View;
13 | import android.view.ViewGroup;
14 | import android.widget.Button;
15 | import android.widget.ImageView;
16 | import android.widget.TextView;
17 | import android.widget.Toast;
18 |
19 | import com.bumptech.glide.Glide;
20 | import com.emon.exampleXMLtoPDF.R;
21 | import com.emon.exampleXMLtoPDF.dummyList.DummyContent;
22 | import com.emon.exampleXMLtoPDF.dummyList.DummyItemRecyclerViewAdapter;
23 | import com.gkemon.XMLtoPDF.PdfGenerator;
24 | import com.gkemon.XMLtoPDF.PdfGeneratorListener;
25 | import com.gkemon.XMLtoPDF.model.FailureResponse;
26 | import com.gkemon.XMLtoPDF.model.SuccessResponse;
27 |
28 | import java.text.DateFormat;
29 | import java.text.SimpleDateFormat;
30 | import java.util.Calendar;
31 |
32 | public class DemoInvoiceFragment extends Fragment {
33 |
34 | private static final String TAG = "InvoiceFragment";
35 | //invoice views edit items
36 | TextView customer_shop_name_tv, customer_address_tv, customer_phone_tv,
37 | customer_order_date_tv, our_delivery_date_tv;
38 | ImageView ivLogo;
39 |
40 | private View finalInvoiceViewToPrint;
41 |
42 | public DemoInvoiceFragment() {
43 | }
44 |
45 |
46 | /**
47 | * IMPORTANT:: We just need to print a invoice_layout LinearLayout,Not the whole RelativeLayout
48 | * So we need to make a view something like "finalInvoiceViewToPrint" which will be print out ignoring
49 | * the rest part of the root layout.
50 | *
51 | * @param root the main view group which is holding the invoice layout. We need to make a
52 | * final invoice view from it (View root) which will be print out ignoring the rest part.
53 | * @return the final invoice view generating from the root view ignoring rest part
54 | * ( generate_invoice_btn button because we don't want to print it.We just print the main part of
55 | * the invoice)
56 | */
57 | private View createInvoiceViewFromRootView(View root) {
58 |
59 | finalInvoiceViewToPrint = root.findViewById(R.id.invoice_layout);
60 | RecyclerView invoice_rv = finalInvoiceViewToPrint.findViewById(R.id.invoice_rv);
61 | customer_shop_name_tv = finalInvoiceViewToPrint.findViewById(R.id.customer_shop_name_tv);
62 | customer_address_tv = finalInvoiceViewToPrint.findViewById(R.id.customer_address_tv);
63 | customer_phone_tv = finalInvoiceViewToPrint.findViewById(R.id.customer_phone_tv);
64 | customer_order_date_tv = finalInvoiceViewToPrint.findViewById(R.id.customer_order_date_tv);
65 | our_delivery_date_tv = finalInvoiceViewToPrint.findViewById(R.id.our_delivery_date_tv);
66 | customer_shop_name_tv.setText(Html.fromHtml("Name: Demo shop name"));
67 | customer_address_tv.setText(Html.fromHtml("Address: " + "Demo shop address"));
68 | customer_phone_tv.setText(Html.fromHtml("Cell No: " + "1234567"));
69 | DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
70 | final String orderDate = format.format(1617976800);
71 | final String deliveryDate = format.format(Calendar.getInstance().getTime());
72 | customer_order_date_tv.setText(Html.fromHtml("Order Date: " + orderDate));
73 | our_delivery_date_tv.setText(Html.fromHtml("Delivery Date: " + deliveryDate));
74 | RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext(), RecyclerView.VERTICAL, false);
75 | invoice_rv.setLayoutManager(layoutManager);
76 | ivLogo=finalInvoiceViewToPrint.findViewById(R.id.iv_logo);
77 | Glide.with(this).load("https://lh6.ggpht.com/9SZhHdv4URtBzRmXpnWxZcYhkgTQurFuuQ8OR7WZ3R7fyTmha77dYkVvcuqMu3DLvMQ=w30").into(ivLogo);
78 | invoice_rv.setAdapter(new DummyItemRecyclerViewAdapter(DummyContent.ITEMS));
79 |
80 | return finalInvoiceViewToPrint;
81 | }
82 |
83 | @Override
84 | public View onCreateView(LayoutInflater inflater, ViewGroup container,
85 | Bundle savedInstanceState) {
86 | View root = inflater.inflate(R.layout.fragment_demo_invoice, container, false);
87 | Button generate_invoice_btn = root.findViewById(R.id.generate_invoice_btn);
88 |
89 | finalInvoiceViewToPrint = createInvoiceViewFromRootView(root);
90 |
91 | generate_invoice_btn.setOnClickListener(v -> {
92 | generatePdf();
93 | });
94 | return root;
95 | }
96 |
97 | public void generatePdf() {
98 | PdfGenerator.getBuilder()
99 | .setContext(requireActivity())
100 | .fromViewSource()
101 | .fromView(finalInvoiceViewToPrint)
102 | /* "fromLayoutXML()" takes array of layout resources.
103 | * You can also invoke "fromLayoutXMLList()" method here which takes list of layout resources instead of array. */
104 | /* It takes default page size like A4,A5. You can also set custom page size in pixel
105 | * by calling ".setCustomPageSize(int widthInPX, int heightInPX)" here. */
106 | .setFileName("demo-invoice")
107 | /* It is file name */
108 | .setFolderNameOrPath("demo-invoice-folder/")
109 | /* It is folder name. If you set the folder name like this pattern (FolderA/FolderB/FolderC), then
110 | * FolderA creates first.Then FolderB inside FolderB and also FolderC inside the FolderB and finally
111 | * the pdf file named "Test-PDF.pdf" will be store inside the FolderB. */
112 | .actionAfterPDFGeneration(PdfGenerator.ActionAfterPDFGeneration.OPEN)
113 | /* It true then the generated pdf will be shown after generated. */
114 | .build(new PdfGeneratorListener() {
115 | @Override
116 | public void onFailure(FailureResponse failureResponse) {
117 | super.onFailure(failureResponse);
118 | Log.d(TAG, "onFailure: " + failureResponse.getErrorMessage());
119 | /* If pdf is not generated by an error then you will findout the reason behind it
120 | * from this FailureResponse. */
121 | //Toast.makeText(MainActivity.this, "Failure : "+failureResponse.getErrorMessage(), Toast.LENGTH_SHORT).show();
122 | Toast.makeText(getContext(), "" + failureResponse.getErrorMessage(), Toast.LENGTH_SHORT).show();
123 | }
124 |
125 | @Override
126 | public void showLog(String log) {
127 | super.showLog(log);
128 | Log.d(TAG, "log: " + log);
129 | /*It shows logs of events inside the pdf generation process*/
130 | }
131 |
132 | @Override
133 | public void onStartPDFGeneration() {
134 |
135 | }
136 |
137 | @Override
138 | public void onFinishPDFGeneration() {
139 |
140 | }
141 |
142 | @Override
143 | public void onSuccess(SuccessResponse response) {
144 | super.onSuccess(response);
145 | /* If PDF is generated successfully then you will find SuccessResponse
146 | * which holds the PdfDocument,File and path (where generated pdf is stored)*/
147 | //Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
148 | Log.d(TAG, "Success: " + response.getPath());
149 |
150 | }
151 | });
152 |
153 | }
154 |
155 | }
--------------------------------------------------------------------------------
/sample/src/main/java/com/emon/exampleXMLtoPDF/dummyList/DummyContent.java:
--------------------------------------------------------------------------------
1 | package com.emon.exampleXMLtoPDF.dummyList;
2 |
3 | import java.util.ArrayList;
4 | import java.util.HashMap;
5 | import java.util.List;
6 | import java.util.Map;
7 |
8 | /**
9 | * Helper class for providing sample content for user interfaces created by
10 | * Android template wizards.
11 | *
12 | * TODO: Replace all uses of this class before publishing your app.
13 | */
14 | public class DummyContent {
15 |
16 | /**
17 | * An array of sample (dummy) items.
18 | */
19 | public static final List ITEMS = new ArrayList();
20 |
21 | /**
22 | * A map of sample (dummy) items, by ID.
23 | */
24 | public static final Map ITEM_MAP = new HashMap();
25 |
26 | private static final int COUNT = 100;
27 |
28 | static {
29 | // Add some sample items.
30 | for (int i = 1; i <= COUNT; i++) {
31 | addItem(createDummyItem(i));
32 | }
33 | }
34 |
35 | private static void addItem(DummyItem item) {
36 | ITEMS.add(item);
37 | ITEM_MAP.put(item.id, item);
38 | }
39 |
40 | private static DummyItem createDummyItem(int position) {
41 | return new DummyItem(String.valueOf(position), "Item " + position, makeDetails(position));
42 | }
43 |
44 | private static String makeDetails(int position) {
45 | StringBuilder builder = new StringBuilder();
46 | builder.append("Details about Item: ").append(position);
47 | for (int i = 0; i < position; i++) {
48 | builder.append("\nMore details information here.");
49 | }
50 | return builder.toString();
51 | }
52 |
53 | /**
54 | * A dummy item representing a piece of content.
55 | */
56 | public static class DummyItem {
57 | public final String id;
58 | public final String content;
59 | public final String details;
60 |
61 | public DummyItem(String id, String content, String details) {
62 | this.id = id;
63 | this.content = content;
64 | this.details = details;
65 | }
66 |
67 | @Override
68 | public String toString() {
69 | return content;
70 | }
71 | }
72 | }
--------------------------------------------------------------------------------
/sample/src/main/java/com/emon/exampleXMLtoPDF/dummyList/DummyItemRecyclerViewAdapter.java:
--------------------------------------------------------------------------------
1 | package com.emon.exampleXMLtoPDF.dummyList;
2 |
3 | import androidx.annotation.NonNull;
4 | import androidx.recyclerview.widget.RecyclerView;
5 |
6 | import android.view.LayoutInflater;
7 | import android.view.View;
8 | import android.view.ViewGroup;
9 | import android.widget.TextView;
10 |
11 | import com.emon.exampleXMLtoPDF.R;
12 | import com.emon.exampleXMLtoPDF.dummyList.DummyContent.DummyItem;
13 |
14 | import java.util.List;
15 |
16 | /**
17 | * {@link RecyclerView.Adapter} that can display a {@link DummyItem}.
18 | * TODO: Replace the implementation with code for your data type.
19 | */
20 | public class DummyItemRecyclerViewAdapter extends
21 | RecyclerView.Adapter {
22 |
23 | private final List mValues;
24 |
25 | public DummyItemRecyclerViewAdapter(List items) {
26 | mValues = items;
27 | }
28 |
29 | @NonNull
30 | @Override
31 | public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
32 | /**
33 | * MUST NEED TO set android:layout_width A FIXED
34 | * VALUE INSTEAD OF "wrap_content" and "match_parent" OTHERWISE SIZING COULD BE MALFORMED
35 | * IN PDF FOR DIFFERENT DEVICE SCREEN
36 | */
37 | View view = LayoutInflater.from(parent.getContext())
38 | .inflate(R.layout.fragment_item, parent, false);
39 | return new ViewHolder(view);
40 | }
41 |
42 | @Override
43 | public void onBindViewHolder(final ViewHolder holder, int position) {
44 | holder.mItem = mValues.get(position);
45 | holder.mIdView.setText(mValues.get(position).id);
46 | holder.mContentView.setText(mValues.get(position).content);
47 | }
48 |
49 | @Override
50 | public int getItemCount() {
51 | return mValues.size();
52 | }
53 |
54 | public static class ViewHolder extends RecyclerView.ViewHolder {
55 | public final View mView;
56 | public final TextView mIdView;
57 | public final TextView mContentView;
58 | public DummyItem mItem;
59 |
60 | public ViewHolder(View view) {
61 | super(view);
62 | mView = view;
63 | mIdView = (TextView) view.findViewById(R.id.item_number);
64 | mContentView = (TextView) view.findViewById(R.id.content);
65 | }
66 |
67 | @NonNull
68 | @Override
69 | public String toString() {
70 | return super.toString() + " '" + mContentView.getText() + "'";
71 | }
72 | }
73 | }
--------------------------------------------------------------------------------
/sample/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/sample/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
14 |
15 |
28 |
29 |
39 |
40 |
50 |
51 |
61 |
71 |
81 |
82 |
92 |
93 |
103 |
104 |
105 |
106 |
107 |
119 |
120 |
121 |
122 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/demo_a4_sized_page.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
8 |
15 |
16 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/demo_barcode.xml:
--------------------------------------------------------------------------------
1 |
2 |
10 |
11 |
22 |
23 |
33 |
34 |
48 |
49 |
62 |
63 |
75 |
76 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/demo_barcode_90_degree_rotated.xml:
--------------------------------------------------------------------------------
1 |
2 |
12 |
13 |
24 |
25 |
35 |
36 |
50 |
51 |
64 |
65 |
77 |
78 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/fragment_demo_invoice.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
16 |
17 |
25 |
26 |
32 |
33 |
34 |
35 |
36 |
41 |
42 |
50 |
51 |
59 |
61 |
62 |
63 |
64 |
72 |
73 |
74 |
81 |
82 |
87 |
88 |
94 |
95 |
101 |
102 |
103 |
104 |
105 |
111 |
112 |
117 |
118 |
124 |
125 |
126 |
127 |
128 |
129 |
130 |
137 |
138 |
139 |
148 |
149 |
154 |
155 |
161 |
162 |
168 |
169 |
170 |
171 |
172 |
180 |
181 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/fragment_item.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
11 |
12 |
19 |
20 |
27 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/item_boxes.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/layout_print.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
16 |
21 |
22 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
124 |
125 |
126 |
127 |
128 |
129 |
130 |
131 |
132 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/layout_print_horizontal_scroll.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
11 |
12 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/layout_test_invoice.xml:
--------------------------------------------------------------------------------
1 |
5 |
6 |
13 |
14 |
21 |
22 |
23 |
24 |
25 |
30 |
31 |
39 |
40 |
48 |
49 |
50 |
51 |
52 |
60 |
61 |
62 |
68 |
69 |
75 |
76 |
84 |
85 |
92 |
93 |
94 |
95 |
96 |
102 |
103 |
110 |
111 |
119 |
120 |
121 |
122 |
123 |
124 |
125 |
132 |
133 |
134 |
143 |
144 |
149 |
150 |
156 |
157 |
163 |
164 |
165 |
166 |
167 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/rv_item_list.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gkemon/Android-XML-to-PDF-Generator/033719775de5b3336f8308beca601dbc365a21fe/sample/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gkemon/Android-XML-to-PDF-Generator/033719775de5b3336f8308beca601dbc365a21fe/sample/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gkemon/Android-XML-to-PDF-Generator/033719775de5b3336f8308beca601dbc365a21fe/sample/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gkemon/Android-XML-to-PDF-Generator/033719775de5b3336f8308beca601dbc365a21fe/sample/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gkemon/Android-XML-to-PDF-Generator/033719775de5b3336f8308beca601dbc365a21fe/sample/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gkemon/Android-XML-to-PDF-Generator/033719775de5b3336f8308beca601dbc365a21fe/sample/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gkemon/Android-XML-to-PDF-Generator/033719775de5b3336f8308beca601dbc365a21fe/sample/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gkemon/Android-XML-to-PDF-Generator/033719775de5b3336f8308beca601dbc365a21fe/sample/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gkemon/Android-XML-to-PDF-Generator/033719775de5b3336f8308beca601dbc365a21fe/sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gkemon/Android-XML-to-PDF-Generator/033719775de5b3336f8308beca601dbc365a21fe/sample/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/sample/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #008577
4 | #00574B
5 | #D81B60
6 |
7 |
--------------------------------------------------------------------------------
/sample/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 |
--------------------------------------------------------------------------------
/sample/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Android XML to Pdf
3 |
4 |
--------------------------------------------------------------------------------
/sample/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/sample/src/test/java/com/emon/exampleXMLtoPDF/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.emon.exampleXMLtoPDF;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':sample' ,
2 | ':xml-to-pdf'
3 | rootProject.name='Android XML to Pdf'
4 |
--------------------------------------------------------------------------------
/xml-to-pdf/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/xml-to-pdf/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 | android {
4 | compileSdkVersion 33
5 | defaultConfig {
6 | minSdkVersion 21
7 | targetSdkVersion 33
8 |
9 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
10 | consumerProguardFiles 'consumer-rules.pro'
11 | }
12 |
13 | buildTypes {
14 | release {
15 | minifyEnabled false
16 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
17 | }
18 | }
19 |
20 | compileOptions {
21 | sourceCompatibility JavaVersion.VERSION_1_8
22 | targetCompatibility JavaVersion.VERSION_1_8
23 | }
24 | namespace 'com.gkemon.XMLtoPDF'
25 |
26 | }
27 |
28 | allprojects {
29 | repositories {
30 | maven { url "https://oss.jfrog.org/libs-snapshot" }
31 | }
32 | }
33 |
34 | dependencies {
35 | implementation fileTree(dir: 'libs', include: ['*.jar'])
36 |
37 | implementation 'androidx.appcompat:appcompat:1.5.1'
38 | implementation 'com.karumi:dexter:6.2.2'
39 | testImplementation 'junit:junit:4.13.2'
40 | androidTestImplementation 'androidx.test.ext:junit:1.1.4'
41 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.0'
42 | implementation 'io.reactivex.rxjava3:rxandroid:3.0.0'
43 | // Because RxAndroid releases are few and far between, it is recommended you also
44 | // explicitly depend on RxJava's latest version for bug fixes and new features.
45 | // (see https://github.com/ReactiveX/RxJava/releases for latest 3.x.x version)
46 | implementation 'io.reactivex.rxjava3:rxjava:3.1.3'
47 | }
48 |
--------------------------------------------------------------------------------
/xml-to-pdf/consumer-rules.pro:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gkemon/Android-XML-to-PDF-Generator/033719775de5b3336f8308beca601dbc365a21fe/xml-to-pdf/consumer-rules.pro
--------------------------------------------------------------------------------
/xml-to-pdf/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/xml-to-pdf/src/androidTest/java/com/gkemon/XMLtoPDF/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.gkemon.XMLtoPDF;
2 |
3 | import android.content.Context;
4 |
5 | import androidx.test.platform.app.InstrumentationRegistry;
6 | import androidx.test.ext.junit.runners.AndroidJUnit4;
7 |
8 | import org.junit.Test;
9 | import org.junit.runner.RunWith;
10 |
11 | import static org.junit.Assert.*;
12 |
13 | /**
14 | * Instrumented test, which will execute on an Android device.
15 | *
16 | * @see Testing documentation
17 | */
18 | @RunWith(AndroidJUnit4.class)
19 | public class ExampleInstrumentedTest {
20 | @Test
21 | public void useAppContext() {
22 | // Context of the app under test.
23 | Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
24 |
25 | assertEquals("com.gkemon.XMLtoPDF.test", appContext.getPackageName());
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/xml-to-pdf/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
12 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/xml-to-pdf/src/main/java/com/gkemon/XMLtoPDF/FileUtils.java:
--------------------------------------------------------------------------------
1 | package com.gkemon.XMLtoPDF;
2 |
3 | /*
4 | * Copyright (C) 2018 OpenIntents.org
5 | *
6 | * Licensed under the Apache License, Version 2.0 (the "License");
7 | * you may not use this file except in compliance with the License.
8 | * You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 |
19 | import android.annotation.SuppressLint;
20 | import android.content.ContentUris;
21 | import android.content.Context;
22 | import android.content.Intent;
23 | import android.database.Cursor;
24 | import android.database.DatabaseUtils;
25 | import android.net.Uri;
26 | import android.os.Build;
27 | import android.os.Environment;
28 | import android.provider.DocumentsContract;
29 | import android.provider.MediaStore;
30 | import android.provider.OpenableColumns;
31 | import android.util.Log;
32 | import android.webkit.MimeTypeMap;
33 |
34 | import androidx.annotation.NonNull;
35 | import androidx.annotation.Nullable;
36 | import androidx.core.content.FileProvider;
37 | import androidx.loader.content.CursorLoader;
38 |
39 | import java.io.BufferedOutputStream;
40 | import java.io.File;
41 | import java.io.FileFilter;
42 | import java.io.FileInputStream;
43 | import java.io.FileOutputStream;
44 | import java.io.IOException;
45 | import java.io.InputStream;
46 | import java.text.DecimalFormat;
47 | import java.util.Comparator;
48 |
49 | public class FileUtils {
50 | public static final String DOCUMENTS_DIR = "documents";
51 | // configured android:authorities in AndroidManifest (https://developer.android.com/reference/android/support/v4/content/FileProvider)
52 | public static final String AUTHORITY = "YOUR_AUTHORITY.provider";
53 | public static final String HIDDEN_PREFIX = ".";
54 | /**
55 | * TAG for log messages.
56 | */
57 | static final String TAG = "FileUtils";
58 | private static final boolean DEBUG = false; // Set to true to enable logging
59 | /**
60 | * File and folder comparator. TODO Expose sorting option method
61 | */
62 | public static Comparator sComparator = (f1, f2) -> {
63 | // Sort alphabetically by lower case, which is much cleaner
64 | return f1.getName().toLowerCase().compareTo(
65 | f2.getName().toLowerCase());
66 | };
67 | /**
68 | * File (not directories) filter.
69 | */
70 | public static FileFilter sFileFilter = file -> {
71 | final String fileName = file.getName();
72 | // Return files only (not directories) and skip hidden files
73 | return file.isFile() && !fileName.startsWith(HIDDEN_PREFIX);
74 | };
75 | /**
76 | * Folder (directories) filter.
77 | */
78 | public static FileFilter sDirFilter = file -> {
79 | final String fileName = file.getName();
80 | // Return directories only and skip hidden directories
81 | return file.isDirectory() && !fileName.startsWith(HIDDEN_PREFIX);
82 | };
83 |
84 | private FileUtils() {
85 | } //private constructor to enforce Singleton pattern
86 |
87 | /**
88 | * Gets the extension of a file name, like ".png" or ".jpg".
89 | *
90 | * @param uri
91 | * @return Extension including the dot("."); "" if there is no extension;
92 | * null if uri was null.
93 | */
94 | public static String getExtension(String uri) {
95 | if (uri == null) {
96 | return null;
97 | }
98 |
99 | int dot = uri.lastIndexOf(".");
100 | if (dot >= 0) {
101 | return uri.substring(dot);
102 | } else {
103 | // No extension.
104 | return "";
105 | }
106 | }
107 |
108 | /**
109 | * @return Whether the URI is a local one.
110 | */
111 | public static boolean isLocal(String url) {
112 | return url != null && !url.startsWith("http://") && !url.startsWith("https://");
113 | }
114 |
115 | /**
116 | * @return True if Uri is a MediaStore Uri.
117 | * @author paulburke
118 | */
119 | public static boolean isMediaUri(Uri uri) {
120 | return "media".equalsIgnoreCase(uri.getAuthority());
121 | }
122 |
123 | /**
124 | * Convert File into Uri.
125 | *
126 | * @param file
127 | * @return uri
128 | */
129 | public static Uri getUri(File file) {
130 | return (file != null) ? Uri.fromFile(file) : null;
131 | }
132 |
133 | /**
134 | * Returns the path only (without file name).
135 | *
136 | * @param file
137 | * @return
138 | */
139 | public static File getPathWithoutFilename(File file) {
140 | if (file != null) {
141 | if (file.isDirectory()) {
142 | // no file to be split off. Return everything
143 | return file;
144 | } else {
145 | String filename = file.getName();
146 | String filepath = file.getAbsolutePath();
147 |
148 | // Construct path without file name.
149 | String pathwithoutname = filepath.substring(0,
150 | filepath.length() - filename.length());
151 | if (pathwithoutname.endsWith("/")) {
152 | pathwithoutname = pathwithoutname.substring(0, pathwithoutname.length() - 1);
153 | }
154 | return new File(pathwithoutname);
155 | }
156 | }
157 | return null;
158 | }
159 |
160 | /**
161 | * @return The MIME type for the given file.
162 | */
163 | public static String getMimeType(File file) {
164 |
165 | String extension = getExtension(file.getName());
166 |
167 | if (extension.length() > 0)
168 | return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.substring(1));
169 |
170 | return "application/octet-stream";
171 | }
172 |
173 | /**
174 | * @return The MIME type for the give Uri.
175 | */
176 | public static String getMimeType(Context context, Uri uri) throws IOException {
177 | File file = new File(getPath(context, uri));
178 | return getMimeType(file);
179 | }
180 |
181 | /**
182 | * @return The MIME type for the give String Uri.
183 | */
184 | public static String getMimeType(Context context, String url) {
185 | String type = context.getContentResolver().getType(Uri.parse(url));
186 | if (type == null) {
187 | type = "application/octet-stream";
188 | }
189 | return type;
190 | }
191 |
192 | /**
193 | * @param uri The Uri to check.
194 | * @return Whether the Uri authority is local.
195 | */
196 | public static boolean isLocalStorageDocument(Uri uri) {
197 | return AUTHORITY.equals(uri.getAuthority());
198 | }
199 |
200 | /**
201 | * @param uri The Uri to check.
202 | * @return Whether the Uri authority is ExternalStorageProvider.
203 | */
204 | public static boolean isExternalStorageDocument(Uri uri) {
205 | return "com.android.externalstorage.documents".equals(uri.getAuthority());
206 | }
207 |
208 | /**
209 | * @param uri The Uri to check.
210 | * @return Whether the Uri authority is DownloadsProvider.
211 | */
212 | public static boolean isDownloadsDocument(Uri uri) {
213 | return "com.android.providers.downloads.documents".equals(uri.getAuthority());
214 | }
215 |
216 | /**
217 | * @param uri The Uri to check.
218 | * @return Whether the Uri authority is MediaProvider.
219 | */
220 | public static boolean isMediaDocument(Uri uri) {
221 | return "com.android.providers.media.documents".equals(uri.getAuthority());
222 | }
223 |
224 | /**
225 | * @param uri The Uri to check.
226 | * @return Whether the Uri authority is Google Photos.
227 | */
228 | public static boolean isGooglePhotosUri(Uri uri) {
229 | return "com.google.android.apps.photos.content".equals(uri.getAuthority());
230 | }
231 |
232 | public static boolean isGoogleDriveUri(Uri uri) {
233 | return "com.google.android.apps.docs.storage.legacy".equals(uri.getAuthority()) ||
234 | "com.google.android.apps.docs.storage".equals(uri.getAuthority());
235 | }
236 |
237 |
238 |
239 | /**
240 | * Get a file path from a Uri. This will get the the path for Storage Access
241 | * Framework Documents, as well as the _data field for the MediaStore and
242 | * other file-based ContentProviders.
243 | *
244 | * Callers should check whether the path is local before assuming it
245 | * represents a local file.
246 | *
247 | * @param context The context.
248 | * @param uri The Uri to query.
249 | * @see #isLocal(String)
250 | * @see #getFile(Context, Uri)
251 | */
252 | public static String getPath(final Context context, final Uri uri) throws IOException {
253 | String absolutePath = getLocalPath(context, uri);
254 | return absolutePath != null ? absolutePath : uri.toString();
255 | }
256 |
257 | private static String getLocalPath(final Context context, final Uri uri) throws IOException {
258 |
259 | if (DEBUG)
260 | Log.d(TAG + " File -",
261 | "Authority: " + uri.getAuthority() +
262 | ", Fragment: " + uri.getFragment() +
263 | ", Port: " + uri.getPort() +
264 | ", Query: " + uri.getQuery() +
265 | ", Scheme: " + uri.getScheme() +
266 | ", Host: " + uri.getHost() +
267 | ", Segments: " + uri.getPathSegments().toString()
268 | );
269 |
270 | final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
271 |
272 | // DocumentProvider
273 | if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
274 | // LocalStorageProvider
275 | if (isLocalStorageDocument(uri)) {
276 | // The path is the id
277 | return DocumentsContract.getDocumentId(uri);
278 | }
279 | // ExternalStorageProvider
280 | else if (isExternalStorageDocument(uri)) {
281 | final String docId = DocumentsContract.getDocumentId(uri);
282 | final String[] split = docId.split(":");
283 | final String type = split[0];
284 |
285 | if ("primary".equalsIgnoreCase(type)) {
286 | return Environment.getExternalStorageDirectory() + "/" + split[1];
287 | } else if ("home".equalsIgnoreCase(type)) {
288 | return Environment.getExternalStorageDirectory() + "/documents/" + split[1];
289 | }
290 | }
291 | // DownloadsProvider
292 | else if (isDownloadsDocument(uri)) {
293 |
294 | final String id = DocumentsContract.getDocumentId(uri);
295 |
296 | if (id != null && id.startsWith("raw:")) {
297 | return id.substring(4);
298 | }
299 |
300 | String[] contentUriPrefixesToTry = new String[]{
301 | "content://downloads/public_downloads",
302 | "content://downloads/my_downloads"
303 | };
304 |
305 | for (String contentUriPrefix : contentUriPrefixesToTry) {
306 | Uri contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), Long.valueOf(id));
307 | String path = getDataColumn(context, contentUri, null, null);
308 | if (path != null) {
309 | return path;
310 | }
311 |
312 | }
313 |
314 | // path could not be retrieved using ContentResolver, therefore copy file to accessible cache using streams
315 | String fileName = getFileName(context, uri);
316 | File cacheDir = getDocumentCacheDir(context);
317 | File file = generateFileName(fileName, cacheDir);
318 | String destinationPath = null;
319 | if (file != null) {
320 | destinationPath = file.getAbsolutePath();
321 | saveFileFromUri(context, uri, destinationPath);
322 | }
323 |
324 | return destinationPath;
325 | }
326 | // MediaProvider
327 | else if (isMediaDocument(uri)) {
328 | final String docId = DocumentsContract.getDocumentId(uri);
329 | final String[] split = docId.split(":");
330 | final String type = split[0];
331 |
332 | Uri contentUri = null;
333 | if ("image".equals(type)) {
334 | contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
335 | } else if ("video".equals(type)) {
336 | contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
337 | } else if ("audio".equals(type)) {
338 | contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
339 | }
340 |
341 | final String selection = "_id=?";
342 | final String[] selectionArgs = new String[]{
343 | split[1]
344 | };
345 |
346 | return getDataColumn(context, contentUri, selection, selectionArgs);
347 | }
348 | //GoogleDriveProvider
349 | else if (isGoogleDriveUri(uri)) {
350 | return getGoogleDriveFilePath(uri, context);
351 | }
352 | }
353 | // MediaStore (and general)
354 | else if ("content".equalsIgnoreCase(uri.getScheme())) {
355 |
356 | // Return the remote address
357 | if (isGooglePhotosUri(uri)) {
358 | return uri.getLastPathSegment();
359 | }
360 | // Google drive legacy provider
361 | else if (isGoogleDriveUri(uri)) {
362 | return getGoogleDriveFilePath(uri, context);
363 | }
364 |
365 | return getDataColumn(context, uri, null, null);
366 | }
367 | // File
368 | else if ("file".equalsIgnoreCase(uri.getScheme())) {
369 | return uri.getPath();
370 | }
371 |
372 | return null;
373 | }
374 |
375 | /**
376 | * Convert Uri into File, if possible.
377 | *
378 | * @return file A local file that the Uri was pointing to, or null if the
379 | * Uri is unsupported or pointed to a remote resource.
380 | * @author paulburke
381 | * @see #getPath(Context, Uri)
382 | */
383 | public static File getFile(Context context, Uri uri) {
384 | if (uri != null) {
385 | String path = getRealPath(context, uri);
386 | if (isLocal(path)) {
387 | return new File(path);
388 | }
389 | }
390 | return null;
391 | }
392 |
393 | /**
394 | * Get the file size in a human-readable string.
395 | *
396 | * @param size
397 | * @return
398 | * @author paulburke
399 | */
400 | public static String getReadableFileSize(int size) {
401 | final int BYTES_IN_KILOBYTES = 1024;
402 | final DecimalFormat dec = new DecimalFormat("###.#");
403 | final String KILOBYTES = " KB";
404 | final String MEGABYTES = " MB";
405 | final String GIGABYTES = " GB";
406 | float fileSize = 0;
407 | String suffix = KILOBYTES;
408 |
409 | if (size > BYTES_IN_KILOBYTES) {
410 | fileSize = size / BYTES_IN_KILOBYTES;
411 | if (fileSize > BYTES_IN_KILOBYTES) {
412 | fileSize = fileSize / BYTES_IN_KILOBYTES;
413 | if (fileSize > BYTES_IN_KILOBYTES) {
414 | fileSize = fileSize / BYTES_IN_KILOBYTES;
415 | suffix = GIGABYTES;
416 | } else {
417 | suffix = MEGABYTES;
418 | }
419 | }
420 | }
421 | return String.valueOf(dec.format(fileSize) + suffix);
422 | }
423 |
424 | /**
425 | * Get the Intent for selecting content to be used in an Intent Chooser.
426 | *
427 | * @return The intent for opening a file with Intent.createChooser()
428 | */
429 | public static Intent createGetContentIntent() {
430 | // Implicitly allow the user to select a particular kind of data
431 | final Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
432 | // The MIME data type filter
433 | intent.setType("*/*");
434 | // Only return URIs that can be opened with ContentResolver
435 | intent.addCategory(Intent.CATEGORY_OPENABLE);
436 | return intent;
437 | }
438 |
439 |
440 | /**
441 | * Creates View intent for given file
442 | *
443 | * @param file
444 | * @return The intent for viewing file
445 | */
446 | public static Intent getViewIntent(Context context, File file) {
447 | //Uri uri = Uri.fromFile(file);
448 | Uri uri = FileProvider.getUriForFile(context, AUTHORITY, file);
449 | Intent intent = new Intent(Intent.ACTION_VIEW);
450 | String url = file.toString();
451 | if (url.contains(".doc") || url.contains(".docx")) {
452 | // Word document
453 | intent.setDataAndType(uri, "application/msword");
454 | } else if (url.contains(".pdf")) {
455 | // PDF file
456 | intent.setDataAndType(uri, "application/pdf");
457 | } else if (url.contains(".ppt") || url.contains(".pptx")) {
458 | // Powerpoint file
459 | intent.setDataAndType(uri, "application/vnd.ms-powerpoint");
460 | } else if (url.contains(".xls") || url.contains(".xlsx")) {
461 | // Excel file
462 | intent.setDataAndType(uri, "application/vnd.ms-excel");
463 | } else if (url.contains(".zip") || url.contains(".rar")) {
464 | // WAV audio file
465 | intent.setDataAndType(uri, "application/x-wav");
466 | } else if (url.contains(".rtf")) {
467 | // RTF file
468 | intent.setDataAndType(uri, "application/rtf");
469 | } else if (url.contains(".wav") || url.contains(".mp3")) {
470 | // WAV audio file
471 | intent.setDataAndType(uri, "audio/x-wav");
472 | } else if (url.contains(".gif")) {
473 | // GIF file
474 | intent.setDataAndType(uri, "image/gif");
475 | } else if (url.contains(".jpg") || url.contains(".jpeg") || url.contains(".png")) {
476 | // JPG file
477 | intent.setDataAndType(uri, "image/jpeg");
478 | } else if (url.contains(".txt")) {
479 | // Text file
480 | intent.setDataAndType(uri, "text/plain");
481 | } else if (url.contains(".3gp") || url.contains(".mpg") || url.contains(".mpeg") ||
482 | url.contains(".mpe") || url.contains(".mp4") || url.contains(".avi")) {
483 | // Video files
484 | intent.setDataAndType(uri, "video/*");
485 | } else {
486 | intent.setDataAndType(uri, "*/*");
487 | }
488 |
489 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
490 | intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
491 | intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
492 | return intent;
493 | }
494 |
495 | public static File getDownloadsDir() {
496 | return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
497 | }
498 |
499 | public static File getDocumentCacheDir(@NonNull Context context) {
500 | File dir = new File(context.getCacheDir(), DOCUMENTS_DIR);
501 | if (!dir.exists()) {
502 | dir.mkdirs();
503 | }
504 | logDir(context.getCacheDir());
505 | logDir(dir);
506 |
507 | return dir;
508 | }
509 |
510 | private static void logDir(File dir) {
511 | if (!DEBUG) return;
512 | Log.d(TAG, "Dir=" + dir);
513 | File[] files = dir.listFiles();
514 | for (File file : files) {
515 | Log.d(TAG, "File=" + file.getPath());
516 | }
517 | }
518 |
519 | @Nullable
520 | public static File generateFileName(@Nullable String name, File directory) {
521 | if (name == null) {
522 | return null;
523 | }
524 |
525 | File file = new File(directory, name);
526 |
527 | if (file.exists()) {
528 | String fileName = name;
529 | String extension = "";
530 | int dotIndex = name.lastIndexOf('.');
531 | if (dotIndex > 0) {
532 | fileName = name.substring(0, dotIndex);
533 | extension = name.substring(dotIndex);
534 | }
535 |
536 | int index = 0;
537 |
538 | while (file.exists()) {
539 | index++;
540 | name = fileName + '(' + index + ')' + extension;
541 | file = new File(directory, name);
542 | }
543 | }
544 |
545 | try {
546 | if (!file.createNewFile()) {
547 | return null;
548 | }
549 | } catch (IOException e) {
550 | Log.w(TAG, e);
551 | return null;
552 | }
553 |
554 | logDir(directory);
555 |
556 | return file;
557 | }
558 |
559 |
560 | private static void saveFileFromUri(Context context, Uri uri, String destinationPath) throws IOException {
561 | InputStream is = null;
562 | BufferedOutputStream bos = null;
563 | is = context.getContentResolver().openInputStream(uri);
564 | bos = new BufferedOutputStream(new FileOutputStream(destinationPath, false));
565 | byte[] buf = new byte[1024];
566 | is.read(buf);
567 | do {
568 | bos.write(buf);
569 | } while (is.read(buf) != -1);
570 | is.close();
571 | bos.close();
572 | }
573 |
574 | public static byte[] readBytesFromFile(String filePath) {
575 |
576 | FileInputStream fileInputStream = null;
577 | byte[] bytesArray = null;
578 |
579 | try {
580 |
581 | File file = new File(filePath);
582 | bytesArray = new byte[(int) file.length()];
583 |
584 | //read file into bytes[]
585 | fileInputStream = new FileInputStream(file);
586 | fileInputStream.read(bytesArray);
587 |
588 | } catch (IOException e) {
589 | e.printStackTrace();
590 | } finally {
591 | if (fileInputStream != null) {
592 | try {
593 | fileInputStream.close();
594 | } catch (IOException e) {
595 | e.printStackTrace();
596 | }
597 | }
598 |
599 | }
600 |
601 | return bytesArray;
602 |
603 | }
604 |
605 | public static File createTempImageFile(Context context, String fileName) throws IOException {
606 | // Create an image file name
607 | File storageDir = new File(context.getCacheDir(), DOCUMENTS_DIR);
608 | return File.createTempFile(fileName, ".jpg", storageDir);
609 | }
610 |
611 | public static String getFileName(@NonNull Context context, Uri uri) throws IOException {
612 | String mimeType = context.getContentResolver().getType(uri);
613 | String filename = null;
614 |
615 | if (mimeType == null && context != null) {
616 | String path = getPath(context, uri);
617 | if (path == null) {
618 | filename = getName(uri.toString());
619 | } else {
620 | File file = new File(path);
621 | filename = file.getName();
622 | }
623 | } else {
624 | Cursor returnCursor = context.getContentResolver().query(uri, null,
625 | null, null, null);
626 | if (returnCursor != null) {
627 | int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
628 | returnCursor.moveToFirst();
629 | filename = returnCursor.getString(nameIndex);
630 | returnCursor.close();
631 | }
632 | }
633 |
634 | return filename;
635 | }
636 |
637 | public static String getName(String filename) {
638 | if (filename == null) {
639 | return null;
640 | }
641 | int index = filename.lastIndexOf('/');
642 | return filename.substring(index + 1);
643 | }
644 |
645 | private static String getGoogleDriveFilePath(Uri uri, Context context) {
646 | Uri returnUri = uri;
647 | Cursor returnCursor = context.getContentResolver().query(returnUri, null, null, null, null);
648 | /*
649 | * Get the column indexes of the data in the Cursor,
650 | * * move to the first row in the Cursor, get the data,
651 | * * and display it.
652 | * */
653 | int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
654 | int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
655 | returnCursor.moveToFirst();
656 |
657 | String name = (returnCursor.getString(nameIndex));
658 | String size = (Long.toString(returnCursor.getLong(sizeIndex)));
659 | File file = new File(context.getCacheDir(), name);
660 | try {
661 | InputStream inputStream = context.getContentResolver().openInputStream(uri);
662 | FileOutputStream outputStream = new FileOutputStream(file);
663 | int read = 0;
664 | int maxBufferSize = 1 * 1024 * 1024;
665 | int bytesAvailable = inputStream.available();
666 | int bufferSize = Math.min(bytesAvailable, maxBufferSize);
667 |
668 | final byte[] buffers = new byte[bufferSize];
669 | while ((read = inputStream.read(buffers)) != -1) {
670 | outputStream.write(buffers, 0, read);
671 | }
672 | inputStream.close();
673 | outputStream.close();
674 | } catch (Exception e) {
675 | e.printStackTrace();
676 | }
677 | return file.getPath();
678 | }
679 |
680 | public static String getRealPath(Context context, Uri fileUri) {
681 | String realPath;
682 | // SDK < API11
683 | realPath = FileUtils.getRealPathFromURI_API19(context, fileUri);
684 | return realPath;
685 | }
686 |
687 |
688 | @SuppressLint("NewApi")
689 | public static String getRealPathFromURI_API19(final Context context, final Uri uri) {
690 |
691 | // DocumentProvider
692 | if (DocumentsContract.isDocumentUri(context, uri)) {
693 | // ExternalStorageProvider
694 | if (isExternalStorageDocument(uri)) {
695 | final String docId = DocumentsContract.getDocumentId(uri);
696 | final String[] split = docId.split(":");
697 | final String type = split[0];
698 |
699 | // This is for checking Main Memory
700 | if ("primary".equalsIgnoreCase(type)) {
701 | if (split.length > 1) {
702 | return Environment.getExternalStorageDirectory() + "/" + split[1];
703 | } else {
704 | return Environment.getExternalStorageDirectory() + "/";
705 | }
706 | // This is for checking SD Card
707 | } else {
708 | return "storage" + "/" + docId.replace(":", "/");
709 | }
710 |
711 | }
712 | // DownloadsProvider
713 | else if (isDownloadsDocument(uri)) {
714 | String fileName = getFilePath(context, uri);
715 | if (fileName != null) {
716 | return Environment.getExternalStorageDirectory().toString() + "/Download/" + fileName;
717 | }
718 |
719 | String id = DocumentsContract.getDocumentId(uri);
720 | if (id.startsWith("raw:")) {
721 | id = id.replaceFirst("raw:", "");
722 | File file = new File(id);
723 | if (file.exists())
724 | return id;
725 | }
726 |
727 | final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
728 | return getDataColumn(context, contentUri, null, null);
729 | }
730 | // MediaProvider
731 | else if (isMediaDocument(uri)) {
732 | final String docId = DocumentsContract.getDocumentId(uri);
733 | final String[] split = docId.split(":");
734 | final String type = split[0];
735 |
736 | Uri contentUri = null;
737 | if ("image".equals(type)) {
738 | contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
739 | } else if ("video".equals(type)) {
740 | contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
741 | } else if ("audio".equals(type)) {
742 | contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
743 | }
744 |
745 | final String selection = "_id=?";
746 | final String[] selectionArgs = new String[]{
747 | split[1]
748 | };
749 |
750 | return getDataColumn(context, contentUri, selection, selectionArgs);
751 | }
752 | }
753 | // MediaStore (and general)
754 | else if ("content".equalsIgnoreCase(uri.getScheme())) {
755 |
756 | // Return the remote address
757 | if (isGooglePhotosUri(uri))
758 | return uri.getLastPathSegment();
759 |
760 | return getDataColumn(context, uri, null, null);
761 | }
762 | // File
763 | else if ("file".equalsIgnoreCase(uri.getScheme())) {
764 | return uri.getPath();
765 | }
766 |
767 | return null;
768 | }
769 |
770 | public static String getDataColumn(Context context, Uri uri, String selection,
771 | String[] selectionArgs) {
772 |
773 | Cursor cursor = null;
774 | final String column = "_data";
775 | final String[] projection = {
776 | column
777 | };
778 |
779 | try {
780 | cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
781 | null);
782 | if (cursor != null && cursor.moveToFirst()) {
783 | final int index = cursor.getColumnIndexOrThrow(column);
784 | return cursor.getString(index);
785 | }
786 | } finally {
787 | if (cursor != null)
788 | cursor.close();
789 | }
790 | return null;
791 | }
792 |
793 |
794 | public static String getFilePath(Context context, Uri uri) {
795 |
796 | final String[] projection = {
797 | MediaStore.MediaColumns.DISPLAY_NAME
798 | };
799 | try (Cursor cursor = context.getContentResolver().query(uri, projection, null, null,
800 | null)) {
801 | if (cursor != null && cursor.moveToFirst()) {
802 | final int index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DISPLAY_NAME);
803 | return cursor.getString(index);
804 | }
805 | }
806 | return null;
807 | }
808 |
809 |
810 | }
--------------------------------------------------------------------------------
/xml-to-pdf/src/main/java/com/gkemon/XMLtoPDF/PdfGenerator.java:
--------------------------------------------------------------------------------
1 | package com.gkemon.XMLtoPDF;
2 |
3 | import android.Manifest;
4 | import android.app.Activity;
5 | import android.content.ActivityNotFoundException;
6 | import android.content.Context;
7 | import android.content.Intent;
8 | import android.content.pm.PackageManager;
9 | import android.graphics.pdf.PdfDocument;
10 | import android.net.Uri;
11 | import android.os.Environment;
12 | import android.os.ParcelFileDescriptor;
13 | import android.os.StrictMode;
14 | import android.provider.DocumentsContract;
15 | import android.text.TextUtils;
16 | import android.view.View;
17 |
18 | import androidx.activity.ComponentActivity;
19 | import androidx.activity.result.ActivityResultLauncher;
20 | import androidx.activity.result.ActivityResultRegistry;
21 | import androidx.activity.result.contract.ActivityResultContracts;
22 | import androidx.annotation.IdRes;
23 | import androidx.annotation.LayoutRes;
24 | import androidx.annotation.NonNull;
25 | import androidx.annotation.Nullable;
26 | import androidx.core.content.ContextCompat;
27 | import androidx.core.content.FileProvider;
28 | import androidx.lifecycle.DefaultLifecycleObserver;
29 | import androidx.lifecycle.LifecycleOwner;
30 |
31 | import com.gkemon.XMLtoPDF.model.FailureResponse;
32 | import com.gkemon.XMLtoPDF.model.SuccessResponse;
33 | import com.karumi.dexter.Dexter;
34 | import com.karumi.dexter.MultiplePermissionsReport;
35 | import com.karumi.dexter.PermissionToken;
36 | import com.karumi.dexter.listener.PermissionDeniedResponse;
37 | import com.karumi.dexter.listener.PermissionGrantedResponse;
38 | import com.karumi.dexter.listener.PermissionRequest;
39 | import com.karumi.dexter.listener.multi.MultiplePermissionsListener;
40 |
41 | import java.io.File;
42 | import java.io.FileOutputStream;
43 | import java.util.ArrayList;
44 | import java.util.Arrays;
45 | import java.util.List;
46 |
47 | import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
48 | import io.reactivex.rxjava3.core.Completable;
49 | import io.reactivex.rxjava3.disposables.Disposable;
50 | import io.reactivex.rxjava3.schedulers.Schedulers;
51 |
52 | public class PdfGenerator {
53 |
54 | public static double postScriptThreshold = 0.75;
55 | public final static int a4HeightInPX = 3508;
56 | public final static int a4WidthInPX = 2480;
57 | public final static int a5HeightInPX = 1748;
58 | public final static int a5WidthInPX = 2480;
59 | public final static String errorMessageOfXMLtoPDFLifecycleObserver = "uri is null from ''xmlToPDFLifecycleObserver'' ";
60 | public static int a4HeightInPostScript = (int) (a4HeightInPX * postScriptThreshold);
61 | public static int a4WidthInPostScript = (int) (a4WidthInPX * postScriptThreshold);
62 |
63 | public static int AS_LIKE_XML_WIDTH = 0, AS_LIKE_XML_HEIGHT = 0;
64 |
65 | public static ContextStep getBuilder() {
66 | return new Builder();
67 | }
68 |
69 | public enum PageSize {
70 | /**
71 | * For standard A4 size page
72 | *
73 | * @deprecated For printing well-formed ISO standard sized papers(like-A4,A5 sized pdf,you
74 | * don't need to be concerned about width and height.Please set width and height to the xml
75 | * with an aspect ratio 1:√2. For example if your xml width is 100 dp then the height of the
76 | * xml will be (100 X √2) = 142 dp. Finally when we print them with any kind of ISO standard
77 | * paper, then they will be auto scaled and fit into the specific paper.
78 | * Reference:http://tolerancing.net/engineering-drawing/paper-size.html
79 | */
80 | @Deprecated
81 | A4,
82 |
83 | /**
84 | * For standard A5 size page
85 | *
86 | * @deprecated For printing well-formed ISO standard sized papers(like-A4,A5 sized pdf,you
87 | * don't need to be concerned about width and height.Please set width and height to the xml
88 | * with an aspect ratio 1:√2. For example if your xml width is 100 dp then the height of the
89 | * xml will be (100 X √2) = 142 dp. Finally when we print them with any kind of ISO standard
90 | * paper, then they will be auto scaled and fit into the specific paper.
91 | * Reference:http://tolerancing.net/engineering-drawing/paper-size.html
92 | */
93 | @Deprecated
94 | A5,
95 | /**
96 | * For print the page as much as they are big.
97 | */
98 | AS_LIKE_XML
99 | }
100 |
101 |
102 | public interface ContextStep {
103 | FromSourceStep setContext(ComponentActivity context);
104 | }
105 |
106 | public interface FromSourceStep {
107 | LayoutXMLSourceIntakeStep fromLayoutXMLSource();
108 |
109 | ViewIDSourceIntakeStep fromViewIDSource();
110 |
111 | ViewSourceIntakeStep fromViewSource();
112 | }
113 |
114 |
115 | public interface ViewSourceIntakeStep {
116 | /**
117 | * @param viewList MUST NEED TO set android:layout_width A FIXED
118 | * VALUE INSTEAD OF "wrap_content" and "match_parent" OTHERWISE SIZING COULD BE MALFORMED
119 | * IN PDF FOR DIFFERENT DEVICE SCREEN
120 | */
121 | FileNameStep fromView(View... viewList);
122 |
123 | /**
124 | * @param viewList MUST NEED TO set android:layout_width A FIXED
125 | * VALUE INSTEAD OF "wrap_content" and "match_parent" OTHERWISE SIZING COULD BE MALFORMED
126 | * IN PDF FOR DIFFERENT DEVICE SCREEN
127 | */
128 | FileNameStep fromViewList(List viewList);
129 | }
130 |
131 | public interface LayoutXMLSourceIntakeStep {
132 | FileNameStep fromLayoutXML(@LayoutRes Integer... layoutXMLs);
133 |
134 | FileNameStep fromLayoutXMLList(@LayoutRes List layoutXMLList);
135 | }
136 |
137 | public interface ViewIDSourceIntakeStep {
138 | /**
139 | * @param containingActivity Host activity where all views reside.
140 | * @param xmlResourceList The view ids which will be printed.
141 | */
142 | FileNameStep fromViewID(@NonNull Activity containingActivity,
143 | @IdRes Integer... xmlResourceList);
144 |
145 | FileNameStep fromViewIDList(@NonNull Activity containingActivity,
146 | @IdRes List xmlResourceList);
147 | }
148 |
149 | public interface PageSizeStep {
150 | FileNameStep setPageSize(PageSize pageSize);
151 | }
152 |
153 | public interface FileNameStep {
154 | Build setFileName(String fileName);
155 | }
156 |
157 | public interface Build {
158 | void build(PdfGeneratorListener pdfGeneratorListener);
159 |
160 | Build setFolderNameOrPath(String folderName);
161 |
162 | Build actionAfterPDFGeneration(ActionAfterPDFGeneration open);
163 |
164 | Build savePDFSharedStorage(XmlToPDFLifecycleObserver xmlToPDFLifecycleObserver);
165 |
166 | }
167 |
168 | public enum ActionAfterPDFGeneration {
169 | OPEN, SHARE, NONE
170 | }
171 |
172 | public static class Builder implements Build
173 | , FileNameStep
174 | , PageSizeStep
175 | , LayoutXMLSourceIntakeStep
176 | , ViewSourceIntakeStep
177 | , ViewIDSourceIntakeStep
178 | , FromSourceStep, ContextStep {
179 | private int pageWidthInPixel = AS_LIKE_XML_WIDTH;
180 | private int pageHeightInPixel = AS_LIKE_XML_HEIGHT;
181 | private Context context;
182 | private PdfGeneratorListener pdfGeneratorListener;
183 | private List viewList = new ArrayList<>();
184 | private String fileName;
185 | private ActionAfterPDFGeneration actionAfterPDFGeneration = ActionAfterPDFGeneration.OPEN;
186 | private String folderName;
187 | private String directoryPath;
188 | private Disposable disposable;
189 | private XmlToPDFLifecycleObserver xmlToPDFLifecycleObserver;
190 |
191 | private void postFailure(String errorMessage) {
192 | FailureResponse failureResponse = new FailureResponse(errorMessage);
193 | postLog(errorMessage);
194 | if (pdfGeneratorListener != null)
195 | pdfGeneratorListener.onFailure(failureResponse);
196 | }
197 |
198 | private void postFailure(Throwable throwable) {
199 | FailureResponse failureResponse = new FailureResponse(throwable);
200 | if (pdfGeneratorListener != null)
201 | pdfGeneratorListener.onFailure(failureResponse);
202 | }
203 |
204 | private void postLog(String logMessage) {
205 | if (pdfGeneratorListener != null)
206 | pdfGeneratorListener.showLog(logMessage);
207 | }
208 |
209 | private void postOnGenerationStart() {
210 | if (pdfGeneratorListener != null)
211 | pdfGeneratorListener.onStartPDFGeneration();
212 | }
213 |
214 | private void postOnGenerationFinished() {
215 | if (pdfGeneratorListener != null)
216 | pdfGeneratorListener.onFinishPDFGeneration();
217 | }
218 |
219 | private void postSuccess(PdfDocument pdfDocument,
220 | File file,
221 | int widthInPS,
222 | int heightInPS) {
223 | if (pdfGeneratorListener != null)
224 | pdfGeneratorListener.onSuccess(
225 | new SuccessResponse(
226 | pdfDocument,
227 | file,
228 | widthInPS,
229 | heightInPS));
230 | }
231 |
232 | private void dealAfterGeneration(ActionAfterPDFGeneration actionAfterPDFGeneration,
233 | File file) {
234 | try {
235 | if (actionAfterPDFGeneration != ActionAfterPDFGeneration.NONE) {
236 | if (file.exists()) {
237 | Intent intent;
238 | if (actionAfterPDFGeneration == ActionAfterPDFGeneration.OPEN)
239 | intent = new Intent(Intent.ACTION_VIEW);
240 | else {
241 | intent = new Intent(Intent.ACTION_SEND);
242 | }
243 | getPDFIntent(file, intent);
244 | try {
245 | context.startActivity(intent);
246 | } catch (ActivityNotFoundException e) {
247 | postFailure(e);
248 | }
249 | } else {
250 | String path = TextUtils.isEmpty(directoryPath) ? "null" : directoryPath;
251 | postFailure("PDF file is not existing in storage. Your Generated path is " + path);
252 | }
253 | } else {
254 | postLog("PDF is generation done but as you set ActionAfterPDFGeneration.NONE" +
255 | " so it is not dealing with it after generation");
256 | }
257 | } catch (Exception exception) {
258 | postFailure("Error occurred while opening the PDF. Error message : " + exception.getMessage());
259 | }
260 | }
261 |
262 | private void dealAfterSavingInSharedStore(ActionAfterPDFGeneration actionAfterPDFGeneration,
263 | Uri uri) {
264 | try {
265 | if (actionAfterPDFGeneration != ActionAfterPDFGeneration.NONE) {
266 | Intent intent;
267 | if (actionAfterPDFGeneration == ActionAfterPDFGeneration.OPEN)
268 | intent = new Intent(Intent.ACTION_VIEW);
269 | else {
270 | intent = new Intent(Intent.ACTION_SEND);
271 | }
272 | getPDFIntent(uri, intent);
273 | try {
274 | context.startActivity(intent);
275 | } catch (ActivityNotFoundException e) {
276 | postFailure(e);
277 | }
278 | } else {
279 | postLog("PDF is generation done but as you set ActionAfterPDFGeneration.NONE" +
280 | " so it is not dealing with it after generation");
281 | }
282 | } catch (Exception exception) {
283 | postFailure("Error occurred while opening the PDF. Error message : " + exception.getMessage());
284 | }
285 |
286 | }
287 |
288 | private void getPDFIntent(File file, Intent intent) {
289 | Uri path = getUriForFile(file);
290 | getPDFIntent(path, intent);
291 | }
292 |
293 | private void getPDFIntent(Uri path, Intent intent) {
294 | if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
295 | intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, path);
296 | }
297 | intent.putExtra(Intent.EXTRA_STREAM, path);
298 | intent.setDataAndType(path, "application/pdf");
299 | intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
300 | intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
301 | }
302 |
303 | private Uri getUriForFile(File file) {
304 | return FileProvider.getUriForFile(
305 | context,
306 | context.getPackageName() + ".xmlToPdf.provider",
307 | file);
308 | }
309 |
310 | /**
311 | * We should reset the value of the page otherwise page size might be differ for each page
312 | */
313 | private void resetValue() {
314 | pageWidthInPixel = AS_LIKE_XML_WIDTH;
315 | pageHeightInPixel = AS_LIKE_XML_HEIGHT;
316 | postScriptThreshold = 0.75;
317 | a4HeightInPostScript = (int) (a4HeightInPX * postScriptThreshold);
318 | }
319 |
320 | private void print() {
321 |
322 | try {
323 | if (context != null) {
324 | PdfDocument document = new PdfDocument();
325 | if (viewList == null || viewList.size() == 0)
326 | postLog("View list null or zero sized");
327 | for (int i = 0; i < viewList.size(); i++) {
328 | resetValue();
329 | View content = viewList.get(i);
330 | if (pageWidthInPixel == AS_LIKE_XML_WIDTH &&
331 | pageHeightInPixel == AS_LIKE_XML_HEIGHT) {
332 | pageHeightInPixel = content.getHeight();
333 | pageWidthInPixel = content.getWidth();
334 |
335 | if (pageHeightInPixel == 0 && pageWidthInPixel == 0) {
336 | //If view was inflated from XML then getHeight() and getWidth()
337 | //So we need to then make it measured.
338 | if (content.getMeasuredWidth() == 0 && content.getMeasuredHeight() == 0) {
339 | /*content.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);*/
340 | content.measure(View.MeasureSpec.makeMeasureSpec(pageWidthInPixel, View.MeasureSpec.UNSPECIFIED),
341 | View.MeasureSpec.makeMeasureSpec(pageHeightInPixel, View.MeasureSpec.UNSPECIFIED));
342 | }
343 | pageHeightInPixel = content.getMeasuredHeight();
344 | pageWidthInPixel = content.getMeasuredWidth();
345 | }
346 |
347 | postScriptThreshold = 1.0;
348 | a4HeightInPostScript = pageHeightInPixel;
349 | }
350 |
351 |
352 | /*Convert page size from pixel into post script because PdfDocument takes
353 | * post script as a size unit*/
354 | pageHeightInPixel = (int) (pageHeightInPixel * postScriptThreshold);
355 | pageWidthInPixel = (int) (pageWidthInPixel * postScriptThreshold);
356 |
357 |
358 | content.measure(View.MeasureSpec.makeMeasureSpec(pageWidthInPixel, View.MeasureSpec.EXACTLY), View.MeasureSpec.UNSPECIFIED);
359 | pageHeightInPixel = (Math.max(content.getMeasuredHeight(), a4HeightInPostScript));
360 |
361 |
362 | PdfDocument.PageInfo pageInfo =
363 | new PdfDocument.PageInfo.Builder((pageWidthInPixel), (pageHeightInPixel), i + 1).create();
364 | PdfDocument.Page page = document.startPage(pageInfo);
365 |
366 | content.layout(0, 0, pageWidthInPixel, pageHeightInPixel);
367 | content.draw(page.getCanvas());
368 |
369 | document.finishPage(page);
370 |
371 | /*Finally invalidate it and request layout for restore the previous state
372 | * of the view as like as the xml. Otherwise for generating PDF by view id,
373 | * the main view is being messed up because this a view is not cloneable and
374 | * being modified in the above view related tasks for printing PDF. */
375 | content.invalidate();
376 | content.requestLayout();
377 |
378 | }
379 |
380 | //This is for prevent crashing while opening generated PDF.
381 | StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
382 | StrictMode.setVmPolicy(builder.build());
383 |
384 | setUpDirectoryPath(context);
385 |
386 | if (TextUtils.isEmpty(directoryPath)) {
387 | postFailure("Cannot find the storage path to create the pdf file.");
388 | return;
389 | }
390 |
391 | if (TextUtils.isEmpty(folderName)) {
392 | directoryPath = directoryPath + "/";
393 | } else if (folderName.contains("/storage/emulated/")) {
394 | directoryPath = folderName + "/";
395 | } else
396 | directoryPath = directoryPath + "/" + folderName + "/";
397 |
398 | directoryPath = directoryPath.replace(" ", "_")
399 | .replace(",", "")
400 | .replace(":", "_");
401 |
402 | File file = new File(directoryPath);
403 | if (!file.exists()) {
404 | if (!file.mkdirs()) {
405 | postLog("Folder is not created." +
406 | "file.mkdirs() is returning false");
407 | }
408 | //Folder is made here
409 | }
410 |
411 | String targetPdf = directoryPath + fileName + ".pdf";
412 |
413 | File fileFinalResult = new File(targetPdf);
414 | //File is created under the folder but not yet written.
415 |
416 | disposeDisposable();
417 | postOnGenerationStart();
418 | //When user want to save pdf in shared storage
419 | if (xmlToPDFLifecycleObserver != null) {
420 | xmlToPDFLifecycleObserver.setPdfSaveListener(uri -> {
421 | if (uri != null)
422 | writePDFOnSavedBlankPDFFile(document, uri);
423 | else {
424 | postFailure(errorMessageOfXMLtoPDFLifecycleObserver);
425 | }
426 | });
427 | Intent intent;
428 | intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
429 | intent.putExtra(Intent.EXTRA_TITLE, fileName);
430 | intent.addCategory(Intent.CATEGORY_OPENABLE);
431 | getPDFIntent(fileFinalResult, intent);
432 | xmlToPDFLifecycleObserver.launchPDFSaverPicker(intent);
433 | } else {
434 | writePDF(document, fileFinalResult);
435 | }
436 | } else {
437 | postFailure("Context is null");
438 | }
439 | } catch (Exception e) {
440 | postFailure(e);
441 | }
442 |
443 | }
444 |
445 | private void writePDFOnSavedBlankPDFFile(PdfDocument document, @NonNull Uri uri) {
446 | try {
447 | if (context == null) {
448 | postFailure("Context is null");
449 | return;
450 | }
451 | ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "w");
452 | FileOutputStream fileOutputStream = new FileOutputStream(pfd.getFileDescriptor());
453 | disposable = Completable.fromAction(() ->
454 | document.writeTo(fileOutputStream))
455 | .subscribeOn(Schedulers.io())
456 | .observeOn(AndroidSchedulers.mainThread())
457 | .doFinally(() -> {
458 | document.close();
459 | fileOutputStream.close();
460 | pfd.close();
461 | disposeDisposable();
462 | postOnGenerationFinished();
463 | })
464 | .subscribe(() -> {
465 | try {
466 | dealAfterSavingInSharedStore(actionAfterPDFGeneration, uri);
467 | postSuccess(
468 | document,
469 | FileUtils.getFile(context, uri),
470 | pageWidthInPixel,
471 | pageHeightInPixel);
472 | } catch (Exception exception) {
473 | postFailure(exception);
474 | }
475 | }, this::postFailure);
476 |
477 | } catch (Exception exception) {
478 | postFailure(exception);
479 | }
480 | }
481 |
482 | private void writePDF(PdfDocument document, File fileFinalResult) {
483 | disposable = Completable.fromAction(() ->
484 | document.writeTo(new FileOutputStream(fileFinalResult)))
485 | .subscribeOn(Schedulers.io())
486 | .observeOn(AndroidSchedulers.mainThread())
487 | .doFinally(() -> {
488 | document.close();
489 | disposeDisposable();
490 | postOnGenerationFinished();
491 | })
492 | .subscribe(() -> {
493 | postSuccess(
494 | document,
495 | fileFinalResult,
496 | pageWidthInPixel,
497 | pageHeightInPixel);
498 |
499 | dealAfterGeneration(actionAfterPDFGeneration, fileFinalResult);
500 | }, this::postFailure);
501 | }
502 |
503 |
504 | private void disposeDisposable() {
505 | if (disposable != null && !disposable.isDisposed())
506 | disposable.dispose();
507 | }
508 |
509 | private void setUpDirectoryPath(Context context) {
510 |
511 | String state = Environment.getExternalStorageState();
512 |
513 | // Make sure it's available
514 | if (!TextUtils.isEmpty(state) && Environment.MEDIA_MOUNTED.equals(state)) {
515 | postLog("Your external storage is mounted");
516 | // We can read and write the media
517 | directoryPath = context.getExternalFilesDir(null) != null ?
518 | context.getExternalFilesDir(null).getAbsolutePath() : "";
519 |
520 | if (TextUtils.isEmpty(directoryPath))
521 | postLog("context.getExternalFilesDir().getAbsolutePath() is returning null.");
522 |
523 | } else {
524 | postLog("Your external storage is unmounted");
525 | // Load another directory, probably local memory
526 | directoryPath = context.getFilesDir() != null ? context.getFilesDir().getAbsolutePath() : "";
527 | if (TextUtils.isEmpty(directoryPath))
528 | postFailure("context.getFilesDir().getAbsolutePath() is also returning null.");
529 | else postLog("PDF file creation path is " + directoryPath);
530 | }
531 | }
532 |
533 | private boolean hasAllPermission(Context context) {
534 | if (context == null) {
535 | postFailure("Context is null");
536 | return false;
537 | }
538 | return ContextCompat.checkSelfPermission(context,
539 | Manifest.permission.READ_EXTERNAL_STORAGE) ==
540 | PackageManager.PERMISSION_GRANTED &&
541 | ContextCompat.checkSelfPermission(context,
542 | Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
543 | PackageManager.PERMISSION_GRANTED;
544 | }
545 |
546 | @Override
547 | public void build(PdfGeneratorListener pdfGeneratorListener) {
548 | this.pdfGeneratorListener = pdfGeneratorListener;
549 | if (hasAllPermission(context) || (xmlToPDFLifecycleObserver != null && android.os.Build.VERSION.SDK_INT > 32)) {
550 | print();
551 | } else {
552 | if (android.os.Build.VERSION.SDK_INT >= 33) {
553 | postFailure("Your current sdk is equal and greater then 33, so you need to set ''xmlToPDFLifecycleObserver'' ." +
554 | "To see example please check this code - https://github.com/Gkemon/Android-XML-to-PDF-Generator/blob/master/sample/src/main/java/com/emon/exampleXMLtoPDF/MainActivity.java" +
555 | ", line-67.");
556 | } else {
557 | postLog("WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE Permission is not given." +
558 | " Permission taking popup (using https://github.com/Karumi/Dexter) is going " +
559 | "to be shown");
560 | }
561 | Dexter.withContext(context)
562 | .withPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE,
563 | Manifest.permission.READ_EXTERNAL_STORAGE)
564 | .withListener(new MultiplePermissionsListener() {
565 | @Override
566 | public void onPermissionsChecked(MultiplePermissionsReport multiplePermissionsReport) {
567 |
568 | for (PermissionDeniedResponse deniedResponse :
569 | multiplePermissionsReport.getDeniedPermissionResponses()) {
570 | postLog("Denied permission: " + deniedResponse.getPermissionName());
571 | }
572 | for (PermissionGrantedResponse grantedResponse :
573 | multiplePermissionsReport.getGrantedPermissionResponses()) {
574 | postLog("Granted permission: " + grantedResponse.getPermissionName());
575 | }
576 | if (multiplePermissionsReport.areAllPermissionsGranted()) {
577 | print();
578 | } else
579 | postLog("All necessary permission is not granted by user. Please do that first");
580 |
581 | }
582 |
583 | @Override
584 | public void onPermissionRationaleShouldBeShown(List list, PermissionToken permissionToken) {
585 |
586 | }
587 | })
588 | .withErrorListener(error -> postLog("Error from Dexter " +
589 | "(https://github.com/Karumi/Dexter) but this library is not maintaining " +
590 | "anymore so please look at this issue - https://github.com/Gkemon/Android-XML-to-PDF-Generator/issues/54#issuecomment-1550307371 " +
591 | error.toString())).check();
592 | }
593 |
594 | }
595 |
596 |
597 | @Override
598 | public FileNameStep fromView(View... viewArrays) {
599 | this.viewList = Utils.getViewListMeasuringRoot(
600 | new ArrayList<>(Arrays.asList(viewArrays)),
601 | pdfGeneratorListener);
602 | return this;
603 | }
604 |
605 | @Override
606 | public FileNameStep fromViewList(List viewList) {
607 | this.viewList = Utils.getViewListMeasuringRoot(viewList, pdfGeneratorListener);
608 | return this;
609 | }
610 |
611 |
612 | @Override
613 | public Build actionAfterPDFGeneration(ActionAfterPDFGeneration actionAfterPDFGeneration) {
614 | this.actionAfterPDFGeneration = actionAfterPDFGeneration;
615 | return this;
616 | }
617 |
618 | @Override
619 | public Build savePDFSharedStorage(XmlToPDFLifecycleObserver xmlToPDFLifecycleObserver) {
620 | this.xmlToPDFLifecycleObserver = xmlToPDFLifecycleObserver;
621 | return this;
622 | }
623 |
624 |
625 | @Override
626 | public FromSourceStep setContext(ComponentActivity context) {
627 | this.context = context;
628 | return this;
629 | }
630 |
631 | @Override
632 | public FileNameStep setPageSize(PageSize pageSize) {
633 | return this;
634 | }
635 |
636 | @Override
637 | public Build setFolderNameOrPath(String folderName) {
638 | this.folderName = folderName;
639 | return this;
640 | }
641 |
642 | @Override
643 | public Build setFileName(String fileName) {
644 | this.fileName = fileName;
645 | return this;
646 | }
647 |
648 |
649 | @Override
650 | public FileNameStep fromViewID(@NonNull Activity activity, @IdRes Integer... xmlResourceList) {
651 | this.viewList = Utils.getViewListFromID(activity, Arrays.asList(xmlResourceList), pdfGeneratorListener);
652 | return this;
653 | }
654 |
655 | @Override
656 | public FileNameStep fromViewIDList(@NonNull Activity activity, List viewIDList) {
657 | this.viewList = Utils.getViewListFromID(activity, viewIDList, pdfGeneratorListener);
658 | return this;
659 | }
660 |
661 |
662 | @Override
663 | public FileNameStep fromLayoutXML(@LayoutRes Integer... layouts) {
664 | this.viewList = Utils.getViewListFromLayout(context, pdfGeneratorListener, Arrays.asList(layouts));
665 | return this;
666 | }
667 |
668 | @Override
669 | public FileNameStep fromLayoutXMLList(@LayoutRes List layoutXMLList) {
670 | this.viewList = Utils.getViewListFromLayout(context, pdfGeneratorListener, layoutXMLList);
671 | return this;
672 | }
673 |
674 | @Override
675 | public LayoutXMLSourceIntakeStep fromLayoutXMLSource() {
676 | return this;
677 | }
678 |
679 | @Override
680 | public ViewIDSourceIntakeStep fromViewIDSource() {
681 | return this;
682 | }
683 |
684 | @Override
685 | public ViewSourceIntakeStep fromViewSource() {
686 | return this;
687 | }
688 | }
689 |
690 | interface PDFSaveListener {
691 | void onBlankPDFCreatedInSharedStorage(@Nullable Uri uri);
692 | }
693 |
694 | public static class XmlToPDFLifecycleObserver implements DefaultLifecycleObserver {
695 | private final ActivityResultRegistry mRegistry;
696 | private ActivityResultLauncher mGetContent;
697 | private PDFSaveListener pdfSaveListener;
698 |
699 | public XmlToPDFLifecycleObserver(@NonNull ComponentActivity componentActivity) {
700 | mRegistry = componentActivity.getActivityResultRegistry();
701 | }
702 |
703 | @Override
704 | public void onCreate(@NonNull LifecycleOwner owner) {
705 | mGetContent = mRegistry.register("saved-pdf-from-xml", owner,
706 | new ActivityResultContracts.StartActivityForResult()
707 | , activityResult -> {
708 | if (pdfSaveListener != null) {
709 | if (activityResult.getData() != null) {
710 | pdfSaveListener.onBlankPDFCreatedInSharedStorage(activityResult.getData().getData());
711 | } else pdfSaveListener.onBlankPDFCreatedInSharedStorage(null);
712 | }
713 | });
714 | }
715 |
716 | public void setPdfSaveListener(PDFSaveListener pdfSaveListener) {
717 | this.pdfSaveListener = pdfSaveListener;
718 | }
719 |
720 | public void launchPDFSaverPicker(Intent intent) {
721 | mGetContent.launch(intent);
722 | }
723 | }
724 |
725 |
726 | }
727 |
--------------------------------------------------------------------------------
/xml-to-pdf/src/main/java/com/gkemon/XMLtoPDF/PdfGeneratorListener.java:
--------------------------------------------------------------------------------
1 | package com.gkemon.XMLtoPDF;
2 |
3 | import com.gkemon.XMLtoPDF.model.FailureResponse;
4 | import com.gkemon.XMLtoPDF.model.SuccessResponse;
5 |
6 | interface PdfGeneratorContract {
7 | void onSuccess(SuccessResponse response);
8 |
9 | void showLog(String log);
10 |
11 | void onStartPDFGeneration();
12 |
13 | void onFinishPDFGeneration();
14 |
15 | void onFailure(FailureResponse failureResponse);
16 | }
17 |
18 | public abstract class PdfGeneratorListener implements PdfGeneratorContract {
19 | @Override
20 | public void showLog(String log) {
21 |
22 | }
23 |
24 | @Override
25 | public void onSuccess(SuccessResponse response) {
26 |
27 | }
28 |
29 | @Override
30 | public void onFailure(FailureResponse failureResponse) {
31 |
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/xml-to-pdf/src/main/java/com/gkemon/XMLtoPDF/Utils.java:
--------------------------------------------------------------------------------
1 | package com.gkemon.XMLtoPDF;
2 |
3 | import android.app.Activity;
4 | import android.content.Context;
5 | import android.view.LayoutInflater;
6 | import android.view.View;
7 |
8 | import androidx.annotation.IdRes;
9 | import androidx.annotation.LayoutRes;
10 | import androidx.annotation.NonNull;
11 |
12 | import com.gkemon.XMLtoPDF.model.FailureResponse;
13 |
14 | import java.util.ArrayList;
15 | import java.util.List;
16 |
17 | /**
18 | * Created by Gk Emon on 8/28/2020.
19 | */
20 | public class Utils {
21 | public static List getViewListFromID(Activity activity,
22 | @IdRes List viewIDList,
23 | PdfGeneratorListener pdfGeneratorListener) {
24 | List viewList = new ArrayList<>();
25 | try {
26 | if (activity != null) {
27 | for (int viewID : viewIDList) {
28 | if (activity.findViewById(android.R.id.content) != null &&
29 | activity.findViewById(android.R.id.content).findViewById(viewID) != null) {
30 | viewList.add(activity.findViewById(android.R.id.content).findViewById(viewID));
31 | } else if (pdfGeneratorListener != null) {
32 | pdfGeneratorListener
33 | .onFailure(new FailureResponse("Your provided activity is " +
34 | "not containing your desired view. Please make sure that you are using " +
35 | "right xml as activity content." +
36 | "Visit the doc for more clearance -" +
37 | " https://github.com/GkEmonGON/Android-XML-to-PDF-Generator/blob/master/README.md"));
38 |
39 | }
40 | }
41 | } else if (pdfGeneratorListener != null) {
42 | pdfGeneratorListener
43 | .onFailure(new FailureResponse("Please provide a valid activity." +
44 | " You are providing null activity."));
45 | }
46 |
47 | } catch (Exception exception) {
48 | if (pdfGeneratorListener != null)
49 | pdfGeneratorListener.onFailure(new FailureResponse(exception, "Error is happening in" +
50 | " getViewListFromID() while creating Java's view object(s) from view ids"));
51 | }
52 |
53 | return viewList;
54 | }
55 |
56 | /**
57 | * @param viewList
58 | * @param pdfGeneratorListener
59 | * @return return views after measuring their roots by UNSPECIFIED otherwise view size won't be
60 | * same in PDF as like as XML.
61 | */
62 | public static List getViewListMeasuringRoot(@NonNull List viewList,
63 | PdfGeneratorListener pdfGeneratorListener) {
64 | List result = new ArrayList<>();
65 | try {
66 | for (View view : viewList) {
67 | if (view != null) {
68 | view.getRootView()
69 | .measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
70 | result.add(view);
71 | }
72 | }
73 | } catch (Exception exception) {
74 | if (pdfGeneratorListener != null)
75 | pdfGeneratorListener.onFailure(new FailureResponse(exception, "Error is happening in" +
76 | " getViewListMeasuringRoot() while creating Java's view object(s) from view ids"));
77 | }
78 |
79 | return result;
80 | }
81 |
82 | public static List getViewListFromLayout(Context context,
83 | PdfGeneratorListener pdfGeneratorListener,
84 | List layoutList) {
85 | List viewList = new ArrayList<>();
86 |
87 | try {
88 | LayoutInflater inflater = (LayoutInflater)
89 | context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
90 |
91 | for (int layout : layoutList) {
92 | View generatedView = inflater.inflate(layout, null);
93 | viewList.add(generatedView);
94 | }
95 |
96 | } catch (Exception e) {
97 | if (pdfGeneratorListener != null)
98 | pdfGeneratorListener.onFailure(new FailureResponse(e,
99 | "Error is happening in" +
100 | " getViewListFromLayout() while creating Java's view object(s) from layout" +
101 | " resources"));
102 | }
103 | return viewList;
104 | }
105 | }
106 |
--------------------------------------------------------------------------------
/xml-to-pdf/src/main/java/com/gkemon/XMLtoPDF/model/FailureResponse.java:
--------------------------------------------------------------------------------
1 | package com.gkemon.XMLtoPDF.model;
2 |
3 | /**
4 | * Created by Gk Emon on 8/30/2020.
5 | */
6 | public class FailureResponse {
7 | Throwable throwable;
8 | String errorMessage;
9 |
10 | public FailureResponse(Throwable throwable) {
11 | this.throwable = throwable;
12 | if(throwable!=null)errorMessage=throwable.getLocalizedMessage();
13 | }
14 | public FailureResponse(Throwable throwable,String errorMessage) {
15 | this.throwable = throwable;
16 | this.errorMessage=errorMessage;
17 | }
18 | public FailureResponse(String errorMessage) {
19 | this.errorMessage=errorMessage;
20 | }
21 |
22 |
23 | public Throwable getThrowable() {
24 | return throwable;
25 | }
26 |
27 | public void setThrowable(Throwable throwable) {
28 | this.throwable = throwable;
29 | }
30 |
31 | public String getErrorMessage() {
32 | return errorMessage;
33 | }
34 |
35 | public void setErrorMessage(String errorMessage) {
36 | this.errorMessage = errorMessage;
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/xml-to-pdf/src/main/java/com/gkemon/XMLtoPDF/model/SuccessResponse.java:
--------------------------------------------------------------------------------
1 | package com.gkemon.XMLtoPDF.model;
2 |
3 | import android.graphics.pdf.PdfDocument;
4 | import android.text.TextUtils;
5 |
6 | import java.io.File;
7 |
8 | /**
9 | * Created by Gk Emon on 8/30/2020.
10 | */
11 | public class SuccessResponse {
12 | PdfDocument pdfDocument;
13 | File file;
14 | String path;
15 | //Because PdfDocument is using PostScript as unit.
16 | int widthInPostScripUnit,heightInPostScripUnit;
17 |
18 |
19 | public SuccessResponse(PdfDocument pdfDocument, File file,int widthInPostScripUnit,int heightInPostScripUnit) {
20 | this.pdfDocument = pdfDocument;
21 | this.file = file;
22 | if (file != null && !TextUtils.isEmpty(file.getAbsolutePath()))
23 | path = file.getAbsolutePath();
24 | this.heightInPostScripUnit=heightInPostScripUnit;
25 | this.widthInPostScripUnit=widthInPostScripUnit;
26 | }
27 |
28 | public PdfDocument getPdfDocument() {
29 | return pdfDocument;
30 | }
31 |
32 | public void setPdfDocument(PdfDocument pdfDocument) {
33 | this.pdfDocument = pdfDocument;
34 | }
35 |
36 | public File getFile() {
37 | return file;
38 | }
39 |
40 | public void setFile(File file) {
41 | this.file = file;
42 | }
43 |
44 | public String getPath() {
45 | if (file != null && !TextUtils.isEmpty(file.getAbsolutePath()))
46 | return file.getAbsolutePath();
47 | return path;
48 | }
49 |
50 | public int getWidthInPostScripUnit() {
51 | return widthInPostScripUnit;
52 | }
53 |
54 | public void setWidthInPostScripUnit(int widthInPostScripUnit) {
55 | this.widthInPostScripUnit = widthInPostScripUnit;
56 | }
57 |
58 | public int getHeightInPostScripUnit() {
59 | return heightInPostScripUnit;
60 | }
61 |
62 | public void setHeightInPostScripUnit(int heightInPostScripUnit) {
63 | this.heightInPostScripUnit = heightInPostScripUnit;
64 | }
65 |
66 | public void setPath(String path) {
67 | this.path = path;
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/xml-to-pdf/src/main/java/com/gkemon/XMLtoPDF/model/XmlToPDFFileProvider.java:
--------------------------------------------------------------------------------
1 | package com.gkemon.XMLtoPDF.model;
2 |
3 | import androidx.core.content.FileProvider;
4 |
5 | public class XmlToPDFFileProvider extends FileProvider {
6 | }
7 |
--------------------------------------------------------------------------------
/xml-to-pdf/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | XML-to-PDF
3 |
4 |
--------------------------------------------------------------------------------
/xml-to-pdf/src/main/res/xml/provider_paths.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
6 |
9 |
12 |
15 |
18 |
19 |
--------------------------------------------------------------------------------
/xml-to-pdf/src/test/java/com/gkemon/XMLtoPDF/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.gkemon.XMLtoPDF;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------