Android Java App Helpers

About the project

A library that provides several functions for developing Android (API 33) apps with Java. The functions may work with later API versions too, but there is no guarantee.

Features

  • Activity base:
    A simple super class for Activities. Display progress-, info- and error dialogs with ease and make profit of some preconfigurations.
  • Android actions helper:
    Provides several functions for interacting with native elements like the camera or the gallery. Don’t bother how to implement this yourself.
  • App internal storage helper:
    Use this simple class to interact with the app internal storage without any effort. Execute CRUD operations and more.
  • PDF DIN-A4 creator:
    A builder class for creating PDF files in DIN-A4 format the easy way. Add text and image block, define padding and more!
1import android.app.AlertDialog;
2import android.content.Context;
3import android.graphics.Color;
4import android.graphics.drawable.Drawable;
5import android.os.Bundle;
6import android.util.Log;
7import android.view.MenuItem;
8import android.widget.LinearLayout;
9import android.widget.ProgressBar;
10import android.widget.Toast;
11 
12import androidx.activity.OnBackPressedCallback;
13import androidx.appcompat.app.AppCompatActivity;
14import androidx.appcompat.content.res.AppCompatResources;
15import androidx.core.app.NavUtils;
16 
17import java.util.Objects;
18 
19/**
20 * <b style="color: red;">This class is designed to work with Android 33.</b>
21 *
22 * @author David Weber
23 */
24public abstract class ActivityBase extends AppCompatActivity {
25 
26 protected AppCompatActivity currentActivity;
27 protected Context context;
28 private AlertDialog progressAlertDialog;
29 
30 protected void onCreate(
31 Bundle savedInstanceState) {
32 
33 super.onCreate(savedInstanceState);
34 this.currentActivity = this;
35 this.context = currentActivity.getApplicationContext();
36 this.getOnBackPressedDispatcher().addCallback(new OnBackPressedCallback(true) {
37 @Override
38 public void handleOnBackPressed() {
39 if (NavUtils.getParentActivityName(currentActivity) != null) {
40 NavUtils.navigateUpFromSameTask(ActivityBase.this); // is needed!
41 } else {
42 Log.v("ActivityBase", "Activity has no parent activity.");
43 finish(); // close app
44 }
45 }
46 });
47 createProgressDialog();
48 }
49 
50 public void displayProgressDialog() {
51 if (!progressAlertDialog.isShowing()) {
52 progressAlertDialog.show();
53 }
54 }
55 
56 public void hideProgressDialog() {
57 progressAlertDialog.dismiss();
58 }
59 
60 private void createProgressDialog() {
61 LinearLayout vLayout = new LinearLayout(currentActivity);
62 vLayout.setOrientation(LinearLayout.VERTICAL);
63 vLayout.setPadding(50, 50, 50, 50);
64 vLayout.addView(new ProgressBar(currentActivity, null, android.R.attr.progressBarStyleLarge));
65 
66 progressAlertDialog = new AlertDialog.Builder(currentActivity)
67 .setCancelable(false)
68 .setView(vLayout)
69 .create();
70 }
71 
72 public void displayToast(
73 Context _this,
74 String message) {
75 
76 Toast.makeText(_this, message, Toast.LENGTH_SHORT).show();
77 }
78 
79 private AlertDialog createAlertDialog(
80 Context _this,
81 String title,
82 String message,
83 Drawable icon) {
84 
85 AlertDialog alert = new AlertDialog.Builder(_this).create();
86 alert.setTitle(title);
87 alert.setMessage(message);
88 alert.setIcon(icon);
89 alert.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", (dialog, which) -> alert.dismiss());
90 return alert;
91 }
92 
93 public void displayInfoDialog(
94 Context _this,
95 String message) {
96 
97 Drawable drawable = AppCompatResources.getDrawable(_this, android.R.drawable.ic_dialog_info);
98 Objects.requireNonNull(drawable).setTint(Color.DKGRAY);
99 createAlertDialog(_this, " ", message, drawable).show();
100 }
101 
102 public void displayErrorDialog(
103 Context _this,
104 String message) {
105 
106 Drawable drawable = AppCompatResources.getDrawable(_this, android.R.drawable.ic_dialog_alert);
107 Objects.requireNonNull(drawable).setTint(Color.DKGRAY);
108 createAlertDialog(_this, " ", message, drawable).show();
109 }
110 
111 public void checkOrUncheckMenuItem(
112 MenuItem menuItem) {
113 
114 menuItem.setChecked(!menuItem.isChecked());
115 }
116 
117}
118 
1import android.app.Activity;
2import android.content.Intent;
3import android.graphics.Bitmap;
4import android.net.Uri;
5import android.util.Log;
6 
7import androidx.activity.ComponentActivity;
8import androidx.activity.result.ActivityResultLauncher;
9import androidx.activity.result.contract.ActivityResultContracts;
10import androidx.appcompat.app.AppCompatActivity;
11import androidx.core.content.FileProvider;
12 
13import com.wedasoft.personalcookbook.BuildConfig; // edit this line
14 
15import java.io.File;
16import java.io.IOException;
17import java.time.Instant;
18 
19/**
20 * <b style="color: red;">This class is designed to work with Android 33.</b>
21 * <br>
22 * This are all used permissions. Enable them only if you need them.
23 * <pre>
24 * {@code
25 * <!-- <uses-feature-->
26 * <!-- android:name="android.hardware.camera"-->
27 * <!-- android:required="false" />-->
28 *
29 * <uses-permission android:name="android.permission.INTERNET" />
30 * <uses-permission android:name="android.permission.READ_PHONE_STATE" />
31 * <uses-permission android:name="android.permission.BLUETOOTH" />
32 * <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
33 * <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
34 * <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
35 * <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
36 * <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
37 * <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
38 * <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
39 * <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
40 * <uses-permission android:name="android.permission.RECORD_AUDIO" />
41 * <uses-permission android:name="android.permission.ACCESS_MEDIA_LOCATION" />
42 * <!-- <uses-permission android:name="android.permission.CAMERA" />-->
43 * <!-- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />-->
44 * <!-- <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />-->
45 * <uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
46 * <uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />
47 * <uses-permission android:name="android.permission.READ_MEDIA_AUDIO" />
48 * }
49 * </pre>
50 */
51public class AndroidActionsHelper {
52 
53 public static class ImagePicker2 {
54 private ActivityResultLauncher<Intent> resultLauncher;
55 private ImagePicker2Callback callbackAfterImageIsPicked;
56 
57 private ImagePicker2() {
58 }
59 
60 /**
61 * Creates and registers the <code>ImagePicker2</code> and the needed <code>ResultLauncher</code>.<br>
62 * Note: Should be used directly in <code>onCreate()</code>.
63 *
64 * @param activity The current activity.
65 */
66 public static ImagePicker2 createAndRegisterInOnCreateOfActivity(AppCompatActivity activity) {
67 ImagePicker2 imagePicker = new ImagePicker2();
68 imagePicker.resultLauncher = activity.registerForActivityResult(
69 new ActivityResultContracts.StartActivityForResult(),
70 activityResult -> {
71 if (activityResult.getResultCode() == Activity.RESULT_OK) {
72 if (activityResult.getData() != null) {
73 Uri uri;
74 try {
75 uri = Uri.parse(activityResult.getData().getDataString());
76 Log.v("ImagePicker2", "Used Uri ='" + uri + "'.");
77 imagePicker.callbackAfterImageIsPicked.run(uri);
78 } catch (IOException e) {
79 Log.v("ImagePicker2", "Couldn't execute the ImagePicker2 correctly.");
80 e.printStackTrace();
81 }
82 }
83 }
84 });
85 return imagePicker;
86 }
87 
88 /**
89 * Picks an image.
90 *
91 * @param callbackAfterImageIsPicked The callback that is executed after the image is picked. It contains the URI to the picked image.
92 * @throws Exception If the <code>ImagePicker2</code> is not created and registered before or if the callback is null.
93 */
94 public void pickImage(ImagePicker2Callback callbackAfterImageIsPicked) throws Exception {
95 if (resultLauncher == null) {
96 throw new Exception("The ImagePicker2 is not created and registered yet. The resultLauncher is null.");
97 }
98 if (callbackAfterImageIsPicked == null) {
99 throw new Exception("The ImagePicker2Callback must not be null");
100 }
101 this.callbackAfterImageIsPicked = callbackAfterImageIsPicked;
102 Intent intent = new Intent();
103 intent.setType("image/*");
104 intent.setAction(Intent.ACTION_GET_CONTENT);
105 resultLauncher.launch(intent);
106 }
107 
108 public interface ImagePicker2Callback {
109 void run(Uri uriOfPickedImage) throws IOException;
110 }
111 }
112 
113 /**
114 * <b>The following steps are required for using the {@code PictureTaker}:</b><br><br>
115 *
116 * <b>1. Add in the {@code <application>} tag in the manifest:</b><br>
117 * <pre>
118 * {@code
119 * <provider
120 * android:name="androidx.core.content.FileProvider"
121 * android:authorities="${applicationId}.provider"
122 * android:exported="false"
123 * android:grantUriPermissions="true">
124 * <meta-data
125 * android:name="android.support.FILE_PROVIDER_PATHS"
126 * android:resource="@xml/provider_paths" />
127 * </provider>
128 * }
129 * </pre>
130 * <b>2. Add the file {@code res/xml/provider_paths.xml} with this content:</b><br>
131 * <pre>
132 * {@code
133 * <?xml version="1.0" encoding="utf-8"?>
134 * <paths xmlns:android="http://schemas.android.com/apk/res/android">
135 * <external-path
136 * name="external_files"
137 * path="." />
138 * <files-path
139 * name="internal_files"
140 * path="." />
141 * </paths>
142 * }
143 * </pre>
144 */
145 public static class PictureTaker {
146 
147 private ActivityResultLauncher<Uri> resultLauncher;
148 private File takenPictureFile;
149 private Uri takenPictureContentUri;
150 private PictureTakerCallback callbackAfterPictureIsTaken;
151 
152 private PictureTaker() {
153 }
154 
155 /**
156 * Creates and registers the <code>PictureTaker</code> and the needed <code>ResultLauncher</code>.<br>
157 * Note: Should be used directly in <code>onCreate()</code>.<br>
158 * Note: The taken picture is saved only temporary and is deleted after the callback is executed.
159 *
160 * @param activity The current activity.
161 */
162 public static PictureTaker createAndRegisterInOnCreateOfActivity(AppCompatActivity activity) {
163 PictureTaker pictureTaker = new PictureTaker();
164 pictureTaker.takenPictureFile = new File(activity.getFilesDir(), "tmp_ImageFromPictureTaker_" + Instant.now().toEpochMilli());
165 pictureTaker.takenPictureContentUri = FileProvider.getUriForFile(
166 activity.getApplicationContext(),
167 BuildConfig.APPLICATION_ID + ".provider",
168 pictureTaker.takenPictureFile);
169 pictureTaker.resultLauncher = activity.registerForActivityResult(
170 new ActivityResultContracts.TakePicture(),
171 pictureTakenSuccess -> {
172 if (pictureTakenSuccess) {
173 pictureTaker.callbackAfterPictureIsTaken.run(pictureTaker.takenPictureContentUri);
174 //noinspection ResultOfMethodCallIgnored
175 pictureTaker.takenPictureFile.delete();
176 }
177 });
178 return pictureTaker;
179 }
180 
181 /**
182 * Takes a picture.
183 *
184 * @param callbackAfterPictureIsTaken The callback that is executed after the picture is taken. It contains the URI to the taken picture.
185 * @throws Exception If the <code>PictureTaker</code> is not created and registered before or if the callback is null.
186 */
187 public void takePicture(PictureTakerCallback callbackAfterPictureIsTaken) throws Exception {
188 if (resultLauncher == null) {
189 throw new Exception("The PictureTaker is not created and registered yet. The resultLauncher is null.");
190 }
191 if (callbackAfterPictureIsTaken == null) {
192 throw new Exception("The PictureTakerCallback must not be null");
193 }
194 this.callbackAfterPictureIsTaken = callbackAfterPictureIsTaken;
195 resultLauncher.launch(takenPictureContentUri);
196 }
197 
198 public interface PictureTakerCallback {
199 void run(Uri takenPictureContentUri);
200 }
201 
202 }
203 
204 @SuppressWarnings("unused")
205 public static class PictureThumbnailTaker {
206 
207 private ActivityResultLauncher<Void> resultLauncher;
208 private PictureThumbnailTakerCallback callbackAfterPictureThumbnailIsTaken;
209 
210 private PictureThumbnailTaker() {
211 }
212 
213 /**
214 * Creates and registers the <code>PictureThumbnailTaker</code> and the needed <code>ResultLauncher</code>.<br>
215 * Note: Should be used directly in <code>onCreate()</code>.
216 *
217 * @param activity The current activity.
218 */
219 public static PictureThumbnailTaker createPictureThumbnailTakerResultLauncher(ComponentActivity activity) {
220 PictureThumbnailTaker pictureThumbnailTaker = new PictureThumbnailTaker();
221 pictureThumbnailTaker.resultLauncher = activity.registerForActivityResult(
222 new ActivityResultContracts.TakePicturePreview(),
223 bitmapOfTakenPictureThumbnail -> {
224 if (bitmapOfTakenPictureThumbnail != null) {
225 pictureThumbnailTaker.callbackAfterPictureThumbnailIsTaken.run(bitmapOfTakenPictureThumbnail);
226 }
227 });
228 return pictureThumbnailTaker;
229 }
230 
231 /**
232 * Takes a picture as thumbnail.
233 *
234 * @param callbackAfterPictureThumbnailIsTaken The callback that is executed after the picture thumbnail is taken. It provides the Bitmap of the taken thumbnail.
235 * @throws Exception If the <code>PictureThumbnailTaker</code> is not created and registered before or if the callback is null.
236 */
237 public void takePictureThumbnail(PictureThumbnailTakerCallback callbackAfterPictureThumbnailIsTaken) throws Exception {
238 if (resultLauncher == null) {
239 throw new Exception("The PictureThumbnailTaker is not created and registered yet. The resultLauncher is null.");
240 }
241 if (callbackAfterPictureThumbnailIsTaken == null) {
242 throw new Exception("The PictureThumbnailTakerCallback must not be null.");
243 }
244 this.callbackAfterPictureThumbnailIsTaken = callbackAfterPictureThumbnailIsTaken;
245 resultLauncher.launch(null);
246 }
247 
248 public interface PictureThumbnailTakerCallback {
249 void run(Bitmap bitmapOfTakenPictureThumbnail);
250 }
251 
252 }
253 
254}
1import android.content.Context;
2import android.graphics.Bitmap;
3 
4import java.io.BufferedOutputStream;
5import java.io.File;
6import java.io.FileOutputStream;
7import java.io.IOException;
8import java.io.OutputStream;
9import java.nio.charset.StandardCharsets;
10import java.nio.file.Files;
11import java.nio.file.StandardOpenOption;
12import java.util.ArrayList;
13import java.util.List;
14 
15/**
16 * <b style="color: red;">This class is designed to work with Android 33.</b>
17 * <br>
18 * The private app internal storage files are located in the directory <b><code>getFilesDir()</code></b>.
19 * <br>
20 * <b>Alle files are stored and loaded in UTF-8.</b>
21 *
22 * @author David Weber
23 */
24public class AppInternalStorageHelper {
25 
26 /**
27 * Checks if a file exists in the <b>app internal storage</b>.
28 *
29 * @return True if the file exists.
30 */
31 public static boolean fileExists(
32 Context context,
33 String filename) {
34 
35 return new File(context.getFilesDir(), filename).exists();
36 }
37 
38 /**
39 * Gets the path of the file with the given file name in the <b>app internal storage</b>.
40 *
41 * @return The file path of the file as String if the file exists, otherwise null.
42 */
43 public static String getPathOfFile(
44 Context context,
45 String filename) {
46 
47 File file = new File(context.getFilesDir(), filename);
48 return file.exists() ? file.getPath() : null;
49 }
50 
51 /**
52 * Creates and writes a file into the <b>app internal storage</b>.
53 *
54 * @return The created file.
55 */
56 public static File createFile(
57 Context context,
58 String filename,
59 String fileContentAsString,
60 boolean overwriteExistingFile)
61 throws IOException {
62 
63 File file = new File(context.getFilesDir(), filename);
64 if (overwriteExistingFile) {
65 Files.deleteIfExists(file.toPath());
66 }
67 
68 return Files.write(file.toPath(), fileContentAsString.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE).toFile();
69 }
70 
71 /**
72 * Creates and writes a file into the <b>app internal storage</b>.
73 */
74 public static void createFile(
75 Context context,
76 String filename,
77 Bitmap fileContentAsBitmap,
78 Bitmap.CompressFormat fileFormat)
79 throws IOException {
80 
81 File file = new File(context.getFilesDir(), filename);
82 OutputStream os = new BufferedOutputStream(new FileOutputStream(file));
83 fileContentAsBitmap.compress(fileFormat, 100, os);
84 os.close();
85 }
86 
87 /**
88 * Reads the content of a file from the <b>app internal storage</b> into bytes.
89 */
90 public static byte[] readFileToBytes(
91 Context context,
92 String filename)
93 throws IOException {
94 
95 File file = new File(context.getFilesDir(), filename);
96 return Files.readAllBytes(file.toPath());
97 }
98 
99 /**
100 * Reads the content of a file from the <b>app internal storage</b> into a <code>String</code>.
101 */
102 public static String readFileToString(
103 Context context,
104 String filename)
105 throws IOException {
106 
107 return new String(readFileToBytes(context, filename), StandardCharsets.UTF_8);
108 }
109 
110 /**
111 * Reads the content of a file from the <b>app internal storage</b> into a <code>List</code> of lines.
112 */
113 public static List<String> readFileToLines(
114 Context context,
115 String filename)
116 throws IOException {
117 
118 File file = new File(context.getFilesDir(), filename);
119 return Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
120 }
121 
122 /**
123 * Deletes all files in the complete <b>app internal storage</b> whose file names begin with the given prefix.
124 */
125 public static void deleteFilesWithPrefix(
126 Context context,
127 String filePrefix) {
128 
129 ArrayList<File> filesToDelete = new ArrayList<>(AppInternalStorageHelper.findFilesWithPrefix(
130 context.getFilesDir(),
131 filePrefix));
132 for (File file : filesToDelete) {
133 //noinspection ResultOfMethodCallIgnored
134 file.delete();
135 }
136 }
137 
138 /**
139 * Finds all files in the complete <b>app internal storage</b> whose file names begin with the given prefix.
140 */
141 public static ArrayList<File> findFilesWithPrefix(
142 File dir,
143 String filePrefix) {
144 
145 ArrayList<File> filesToReturn = new ArrayList<>();
146 File[] listedFiles = dir.listFiles();
147 if (listedFiles != null) {
148 for (File listedFile : listedFiles) {
149 if (listedFile.isDirectory()) {
150 findFilesWithPrefix(listedFile, filePrefix);
151 } else {
152 if (listedFile.getName().startsWith(filePrefix)) {
153 filesToReturn.add(listedFile);
154 }
155 }
156 }
157 }
158 return filesToReturn;
159 }
160 
161}
162 
1import android.graphics.Bitmap;
2import android.graphics.Canvas;
3import android.graphics.Color;
4import android.graphics.Paint;
5import android.graphics.drawable.BitmapDrawable;
6import android.graphics.drawable.Drawable;
7import android.graphics.pdf.PdfDocument;
8import android.graphics.pdf.PdfDocument.Page;
9import android.graphics.pdf.PdfDocument.PageInfo;
10import android.graphics.text.LineBreaker;
11import android.os.Environment;
12import android.text.Layout;
13import android.text.StaticLayout;
14import android.text.TextPaint;
15import android.util.Log;
16 
17import java.io.File;
18import java.io.FileOutputStream;
19import java.io.IOException;
20import java.util.ArrayList;
21import java.util.List;
22 
23/**
24 * <b style="color: red;">This class is designed to work with Android 33.</b>
25 *
26 * @author David Weber
27 */
28public class PdfDinA4Creator {
29 private static class ContentBlock<Type> {
30 public Type type;
31 public Integer prefWidth;
32 public Integer prefHeight;
33 
34 public ContentBlock(Type type) {
35 this.type = type;
36 }
37 
38 public ContentBlock(Type type, Integer prefWidth, Integer prefHeight) {
39 this.type = type;
40 this.prefWidth = prefWidth;
41 this.prefHeight = prefHeight;
42 }
43 }
44 
45 private static final double ONE_CM_AS_INCH = 0.39370079;
46 public static final int SIZE_OF_ONE_CM = (int) (ONE_CM_AS_INCH * 72);
47 private final int widthDinA4 = (int) (8.27d * 72); // inches to points
48 private final int heightDinA4 = (int) (11.69d * 72); // inches to points
49 
50 private int paddingLeftAndRight;
51 private final List<ContentBlock<?>> contentBlocks;
52 
53 public PdfDinA4Creator() {
54 contentBlocks = new ArrayList<>();
55 }
56 
57 /**
58 * Sets the left and right padding of the document.
59 *
60 * @param paddingLeftAndRight The used padding for left and right.
61 * @return This PdfDinA4Creator.
62 */
63 public PdfDinA4Creator setPaddingLeftAndRight(int paddingLeftAndRight) {
64 this.paddingLeftAndRight = paddingLeftAndRight;
65 return this;
66 }
67 
68 /**
69 * Adds the given content as {@link ContentBlock} to the PDF.<br>
70 * A {@link ContentBlock} inserts a line break after its end.<br>
71 * The inserted content is left aligned and breaks when the document end is reached its line.
72 *
73 * @param content The content to add.
74 * @return This PdfDinA4Creator.
75 */
76 public PdfDinA4Creator addContentBlock(CharSequence content) {
77 if (content == null) {
78 throw new NullPointerException("Content must not be null!");
79 }
80 TextPaint textPaint = new TextPaint();
81 textPaint.setColor(Color.BLACK);
82 textPaint.setTextSize(12);
83 StaticLayout staticLayout = StaticLayout.Builder.obtain(
84 content,
85 0,
86 content.length(),
87 textPaint,
88 getDinA4WidthMinusPaddingLeftAndRight())
89 .setText(content)
90 .setAlignment(Layout.Alignment.ALIGN_NORMAL)
91 .setLineSpacing(0.0f, 1.0f)
92 .setIncludePad(false)
93 .setBreakStrategy(LineBreaker.BREAK_STRATEGY_SIMPLE)
94 .setHyphenationFrequency(Layout.HYPHENATION_FREQUENCY_NONE)
95 .build();
96 contentBlocks.add(new ContentBlock<>(staticLayout));
97 return this;
98 }
99 
100 /**
101 * Adds the given content as {@link ContentBlock} to the PDF.<br>
102 * A {@link ContentBlock} inserts a line break after its end.<br>
103 * By defining the arguments "prefWidth" and "prefHeight", the content is scaled by respecting its width-height-aspect-ratio.
104 * If the width or height is bigger than the max available size, the content is scaled to the max available size.
105 *
106 * @param content The content to add.
107 * @param prefWidth The preferred width to scale the content to.
108 * @param prefHeight The preferred height to scale the content to.
109 * @return This PdfDinA4Creator.
110 */
111 public PdfDinA4Creator addContentBlock(Bitmap content, Integer prefWidth, Integer prefHeight) {
112 if (content == null) {
113 throw new NullPointerException("Content must not be null!");
114 }
115 
116 if (content.getHeight() > content.getWidth()) {
117 content = rescaleBitmapByPrefWidth(content, prefWidth);
118 content = rescaleBitmapByPrefHeight(content, prefHeight);
119 } else {
120 content = rescaleBitmapByPrefHeight(content, prefHeight);
121 content = rescaleBitmapByPrefWidth(content, prefWidth);
122 }
123 
124 if (content.getHeight() > heightDinA4) {
125 throw new RuntimeException("The Bitmap is to big to fit on a single DIN A4 sheet. Either implement logic here or don't allow it.");
126 }
127 if (content.getWidth() > widthDinA4) {
128 throw new RuntimeException("The Bitmap is to big to fit on a single DIN A4 sheet. Either implement logic here or don't allow it.");
129 }
130 
131 contentBlocks.add(new ContentBlock<>(content, prefWidth, prefHeight));
132 return this;
133 }
134 
135 /**
136 * Adds the given content as {@link ContentBlock} to the PDF.<br>
137 * A {@link ContentBlock} inserts a line break after its end.<br>
138 * By defining the arguments "prefWidth" and "prefHeight", the content is scaled by respecting its width-height-aspect-ratio.
139 * If the width or height is bigger than the max available size, the content is scaled to the max available size.
140 *
141 * @param content The content to add.
142 * @param prefWidth The preferred width to scale the content to.
143 * @param prefHeight The preferred height to scale the content to.
144 * @return This PdfDinA4Creator.
145 */
146 public PdfDinA4Creator addContentBlock(Drawable content, Integer prefWidth, Integer prefHeight) {
147 if (content == null) {
148 throw new NullPointerException("Content must not be null!");
149 }
150 return addContentBlock(convertDrawableToBitmap(content), prefWidth, prefHeight);
151 }
152 
153 /**
154 * Creates the PDF-Document.
155 *
156 * @return The created PDF-Document.
157 */
158 public PdfDocument createAndGet() {
159 PdfDocument document = new PdfDocument();
160 Page currentPage = initNextPage(document, null, widthDinA4, heightDinA4);
161 
162 int currentCoordinateSystemStartY = 0;
163 for (ContentBlock<?> contentBlock : contentBlocks) {
164 if (contentBlock.type instanceof StaticLayout) {
165 StaticLayout layout = (StaticLayout) contentBlock.type;
166 if (layout.getHeight() > heightDinA4) {
167 throw new RuntimeException("The StaticLayout representing is to big to fit on a single DIN A4 sheet. Please split it into several ContentBlocks.");
168 }
169 if (currentCoordinateSystemStartY + layout.getHeight() > heightDinA4) { // layout passt nicht mehr komplett auf die aktuelle Seite drauf
170 currentPage = initNextPage(document, currentPage, widthDinA4, heightDinA4);
171 currentCoordinateSystemStartY = 0;
172 }
173 
174 currentPage.getCanvas().translate(paddingLeftAndRight, 0);
175 layout.draw(currentPage.getCanvas());
176 currentPage.getCanvas().translate(-paddingLeftAndRight, layout.getHeight());
177 currentCoordinateSystemStartY += layout.getHeight();
178 continue;
179 }
180 if (contentBlock.type instanceof Bitmap) {
181 Bitmap bitmap = (Bitmap) contentBlock.type;
182 
183 Paint paint = new Paint();
184 paint.setAntiAlias(true);
185 paint.setFilterBitmap(true);
186 paint.setDither(true);
187 
188 if (currentCoordinateSystemStartY + bitmap.getHeight() > heightDinA4) { // layout passt nicht mehr komplett auf die aktuelle Seite drauf
189 currentPage = initNextPage(document, currentPage, widthDinA4, heightDinA4);
190 currentCoordinateSystemStartY = 0;
191 }
192 
193 currentPage.getCanvas().translate(paddingLeftAndRight, 0);
194 currentPage.getCanvas().drawBitmap(bitmap, 0, 0, paint);
195 currentPage.getCanvas().translate(-paddingLeftAndRight, bitmap.getHeight());
196 currentCoordinateSystemStartY += bitmap.getHeight();
197 }
198 }
199 document.finishPage(currentPage);
200 return document;
201 }
202 
203 public static void savePdfIntoDownloadsDirectory(String fileName, PdfDocument pdfDocument) throws IOException {
204 String filePathInDownloadsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + "/" + fileName;
205 File file = new File(filePathInDownloadsDir);
206 pdfDocument.writeTo(new FileOutputStream(file));
207 pdfDocument.close();
208 }
209 
210 @SuppressWarnings("PointlessArithmeticExpression")
211 private int getDinA4HeightMinusPaddingTopAndBottom() {
212 return heightDinA4 - 0 * 2;
213 }
214 
215 private int getDinA4WidthMinusPaddingLeftAndRight() {
216 return widthDinA4 - paddingLeftAndRight * 2;
217 }
218 
219 @SuppressWarnings("SameParameterValue")
220 private Page initNextPage(PdfDocument document, Page currentPage, int width, int height) {
221 if (currentPage != null) {
222 document.finishPage(currentPage);
223 }
224 Page nextPage = document.startPage(new PageInfo.Builder(width, height, document.getPages().size() + 1).create());
225 nextPage.getCanvas().save();
226 return nextPage;
227 }
228 
229 private Bitmap convertDrawableToBitmap(Drawable drawable) {
230 if (drawable instanceof BitmapDrawable) {
231 return ((BitmapDrawable) drawable).getBitmap();
232 }
233 
234 Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
235 Canvas canvas = new Canvas(bitmap);
236 drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
237 drawable.draw(canvas);
238 
239 return bitmap;
240 }
241 
242 private Bitmap scaleProportionalToNewHeight(Bitmap bitmap, int newHeight) {
243 float aspectRatio = bitmap.getWidth() / (float) bitmap.getHeight();
244 int width = Math.round(newHeight * aspectRatio);
245 return Bitmap.createScaledBitmap(bitmap, width, newHeight, true);
246 }
247 
248 private Bitmap scaleProportionalToNewWidth(Bitmap bitmap, int newWidth) {
249 float aspectRatio = bitmap.getWidth() / (float) bitmap.getHeight();
250 int height = Math.round(newWidth / aspectRatio);
251 return Bitmap.createScaledBitmap(bitmap, newWidth, height, true);
252 }
253 
254 private Bitmap rescaleBitmapByPrefHeight(Bitmap bitmap, Integer prefHeight) {
255 if (prefHeight == null) {
256 if (bitmap.getHeight() > getDinA4HeightMinusPaddingTopAndBottom()) {
257 bitmap = scaleProportionalToNewHeight(bitmap, getDinA4HeightMinusPaddingTopAndBottom());
258 }
259 } else {
260 if (prefHeight > getDinA4HeightMinusPaddingTopAndBottom()) {
261 Log.w("PdfDinA4Creator", "contentBlock.prefHeight is not null, but it is bigger than the available space. Using the max. available space.");
262 bitmap = scaleProportionalToNewHeight(bitmap, getDinA4HeightMinusPaddingTopAndBottom());
263 } else {
264 bitmap = scaleProportionalToNewHeight(bitmap, prefHeight);
265 }
266 }
267 return bitmap;
268 }
269 
270 private Bitmap rescaleBitmapByPrefWidth(Bitmap bitmap, Integer prefWidth) {
271 if (prefWidth == null) {
272 if (bitmap.getWidth() > getDinA4WidthMinusPaddingLeftAndRight()) {
273 bitmap = scaleProportionalToNewWidth(bitmap, getDinA4WidthMinusPaddingLeftAndRight());
274 }
275 } else {
276 if (prefWidth > getDinA4WidthMinusPaddingLeftAndRight()) {
277 Log.w("PdfDinA4Creator", "contentBlock.prefWidth is not null, but it is bigger than the available space. Using the max. available space.");
278 bitmap = scaleProportionalToNewWidth(bitmap, getDinA4WidthMinusPaddingLeftAndRight());
279 } else {
280 bitmap = scaleProportionalToNewWidth(bitmap, prefWidth);
281 }
282 }
283 return bitmap;
284 }
285 
286}
287 
288