Java Examples for android.graphics.pdf.PdfDocument
The following java examples will help you to understand the usage of android.graphics.pdf.PdfDocument. These source code samples are taken from different open source projects.
Example 1
| Project: m2e-master File: MainActivity.java View source code |
public void run() {
// Create a shiny new (but blank) PDF document in memory
// We want it to optionally be printable, so add PrintAttributes
// and use a PrintedPdfDocument. Simpler: new PdfDocument().
PrintAttributes printAttrs = new PrintAttributes.Builder().setColorMode(PrintAttributes.COLOR_MODE_COLOR).setMediaSize(PrintAttributes.MediaSize.NA_LETTER).setResolution(new Resolution("zooey", PRINT_SERVICE, 300, 300)).setMinMargins(Margins.NO_MARGINS).build();
PdfDocument document = new PrintedPdfDocument(this, printAttrs);
// crate a page description
PageInfo pageInfo = new PageInfo.Builder(300, 300, 1).create();
// create a new page from the PageInfo
Page page = document.startPage(pageInfo);
// repaint the user's text into the page
View content = findViewById(R.id.textArea);
content.draw(page.getCanvas());
// do final processing of the page
document.finishPage(page);
// accept a String/CharSequence. Meh.
try {
File pdfDirPath = new File(getFilesDir(), "pdfs");
pdfDirPath.mkdirs();
File file = new File(pdfDirPath, "pdfsend.pdf");
Uri contentUri = FileProvider.getUriForFile(this, "com.example.fileprovider", file);
os = new FileOutputStream(file);
document.writeTo(os);
document.close();
os.close();
shareDocument(contentUri);
} catch (IOException e) {
throw new RuntimeException("Error generating file", e);
}
}Example 2
| Project: GDG-master File: PDFCreateActivity.java View source code |
public void run() {
// Get the directory for the app's private pictures directory.
final File file = new File(Environment.getExternalStorageDirectory(), "demo.pdf");
if (file.exists()) {
file.delete();
}
FileOutputStream out = null;
try {
out = new FileOutputStream(file);
PdfDocument document = new PdfDocument();
Point windowSize = new Point();
getWindowManager().getDefaultDisplay().getSize(windowSize);
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(windowSize.x, windowSize.y, 1).create();
PdfDocument.Page page = document.startPage(pageInfo);
View content = getWindow().getDecorView();
content.draw(page.getCanvas());
document.finishPage(page);
document.writeTo(out);
document.close();
out.flush();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(PDFCreateActivity.this, "File created: " + file.getAbsolutePath(), Toast.LENGTH_LONG).show();
}
});
} catch (Exception e) {
Log.d("TAG_PDF", "File was not created: " + e.getMessage());
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}Example 3
| Project: IM-timetracking-master File: PdfExporter.java View source code |
@Override
public File export() {
// get trackings
List<Tracking> trackings = tracker.getTrackings();
if (trackings == null || trackings.isEmpty())
return null;
Timber.d("exporting %d trackings to pdf", trackings.size());
// create file
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
String todayString = sdf.format(new Date(System.currentTimeMillis()));
String pdfFileName = "im-timetracking-" + todayString + ".pdf";
File pdfFile = new File(FileUtil.appDir, pdfFileName);
// create pdf
TextPaint p = new TextPaint();
p.setTextSize(10);
p.setColor(Color.BLACK);
p.setTypeface(Typeface.MONOSPACE);
p.setAntiAlias(true);
TextPaint gp = new TextPaint(p);
gp.setColor(ctx.getResources().getColor(R.color.im_green));
gp.setFakeBoldText(true);
PdfDocument doc = new PdfDocument();
int a4Width = (int) (210 / 25.4 * 72);
int a4Height = (int) (297 / 25.4 * 72);
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(a4Width, a4Height, 1).create();
PdfDocument.Page page = doc.startPage(pageInfo);
Canvas c = page.getCanvas();
int padding = ctx.getResources().getInteger(R.integer.export_pdf_page_padding);
String unnamed = ctx.getString(R.string.list_item_tracking_unnamed_title);
StringBuilder sb = new StringBuilder();
long totalDuration = 0;
// prepare entries
for (Tracking t : trackings) {
sb.append(sdf.format(new Date(t.getCreated()))).append(" ");
sb.append(TimeUtil.getTimeString(t.getDuration())).append(" | ");
sb.append(TextUtils.isEmpty(t.getTitle()) ? unnamed : t.getTitle());
sb.append("\n");
totalDuration += t.getDuration();
}
// write entries - TODO care about pagination at some point
c.save();
c.translate(padding, padding);
StaticLayout sl = new StaticLayout(sb.toString(), p, a4Width / 5 * 4, Layout.Alignment.ALIGN_NORMAL, 1.0f, 1.0f, false);
sl.draw(c);
// write total
c.translate(0, sl.getHeight());
sb.setLength(0);
sb.append(ctx.getResources().getString(R.string.total));
sb.append(TimeUtil.getTimeString(totalDuration));
sl = new StaticLayout(sb.toString(), gp, a4Width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 1.0f, false);
sl.draw(c);
c.restore();
// draw icon
c.save();
c.translate(a4Width * 0.80f, a4Height * 0.85f);
Paint iconPaint = new Paint();
iconPaint.setAlpha(42);
Bitmap appIcon = BitmapFactory.decodeResource(ctx.getResources(), R.mipmap.ic_launcher);
appIcon = Bitmap.createScaledBitmap(appIcon, 80, 80, true);
c.drawBitmap(appIcon, 0, 0, iconPaint);
c.restore();
appIcon.recycle();
doc.finishPage(page);
try {
// write to file
if (pdfFile.exists()) {
pdfFile.delete();
}
Timber.v("writing pdf file %s", pdfFile.getAbsolutePath());
doc.writeTo(new FileOutputStream(pdfFile));
} catch (IOException e) {
Timber.e(e, "failed writing pdf file");
return null;
} finally {
doc.close();
}
return pdfFile;
}Example 4
| Project: PrintingFrameworkSample-master File: CustomDocumentPrintAdapter.java View source code |
@Override
public void onWrite(android.print.PageRange[] pages, android.os.ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback) {
if (mPdfDocument == null) {
Log.e("print", "error mPdfDocument is null.");
return;
}
PdfDocument.Page page = mPdfDocument.startPage(0);
if (cancellationSignal.isCanceled()) {
callback.onWriteCancelled();
mPdfDocument.close();
mPdfDocument = null;
return;
}
onDraw(page.getCanvas());
mPdfDocument.finishPage(page);
try {
mPdfDocument.writeTo(new FileOutputStream(destination.getFileDescriptor()));
} catch (IOException e) {
callback.onWriteFailed(e.toString());
return;
} finally {
mPdfDocument.close();
mPdfDocument = null;
}
callback.onWriteFinished(pages);
}Example 5
| Project: bitesize-kitkat-master File: PrintShopPrintDocumentAdapter.java View source code |
@Override
public void onWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, final WriteResultCallback callback) {
// Register a cancellation listener
cancellationSignal.setOnCancelListener(new CancellationSignal.OnCancelListener() {
@Override
public void onCancel() {
// If cancelled then ensure that the PDF doc gets thrown away
pdfDocument.close();
pdfDocument = null;
// And callback
callback.onWriteCancelled();
}
});
// Iterate through the pages
for (int currentPageNumber = 0; currentPageNumber < pageCount; currentPageNumber++) {
// Has this page been requested?
if (!pageRangesContainPage(currentPageNumber, pages)) {
// Skip this page
continue;
}
// Start the current page
PdfDocument.Page page = pdfDocument.startPage(currentPageNumber);
// Get the canvas for this page
Canvas canvas = page.getCanvas();
// Draw on the page
drawPage(currentPageNumber, canvas);
// Finish the page
pdfDocument.finishPage(page);
}
// Attempt to send the completed doc out
try {
pdfDocument.writeTo(new FileOutputStream(destination.getFileDescriptor()));
} catch (IOException e) {
callback.onWriteFailed(e.toString());
return;
} finally {
pdfDocument.close();
pdfDocument = null;
}
// The print is complete
callback.onWriteFinished(pages);
}Example 6
| Project: rgb-tool-master File: RGBToolPrintPaletteAdapter.java View source code |
@Override
public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras) {
// Create a new PdfDocument with the requested page attributes
pdfDocument = new PrintedPdfDocument(context, newAttributes);
// Respond to cancellation request
if (cancellationSignal.isCanceled()) {
Toast.makeText(context, context.getString(R.string.print_job_canceled), Toast.LENGTH_SHORT).show();
callback.onLayoutCancelled();
return;
}
// Compute the expected number of printed pages
int pages = computePageCount(newAttributes);
if (pages > 0) {
// Return print information to print framework
PrintDocumentInfo info = new PrintDocumentInfo.Builder("rgbtool_" + filename + "_palette.pdf").setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT).setPageCount(pages).build();
// Content layout reflow is complete
callback.onLayoutFinished(info, true);
} else {
// Otherwise report an error to the print framework
callback.onLayoutFailed("Page count calculation failed.");
}
}Example 7
| Project: android-print-plugin-cups-master File: SharePrinterActivity.java View source code |
@Override
public void onWrite(final PageRange[] pageRanges, final ParcelFileDescriptor destination, final CancellationSignal cancellationSignal, final WriteResultCallback callback) {
if (pageRanges.length == 0 || !(pageRanges[0].getStart() <= 0 && pageRanges[0].getEnd() >= 0 || pageRanges[0] == PageRange.ALL_PAGES)) {
Log.d(TAG, "Saving PDF failed - no valid page range");
return;
}
if (cancellationSignal.isCanceled()) {
callback.onWriteCancelled();
pdf.close();
pdf = null;
return;
}
PdfDocument.Page page = pdf.startPage(0);
drawPage(page);
pdf.finishPage(page);
Log.d(TAG, "Saving PDF");
try {
pdf.writeTo(new FileOutputStream(destination.getFileDescriptor()));
Log.w(TAG, "Saving PDF succeeded");
} catch (IOException e) {
Log.w(TAG, "Saving PDF failed: " + e.toString());
callback.onWriteFailed(e.toString());
return;
} finally {
pdf.close();
pdf = null;
}
callback.onWriteFinished(new PageRange[] { new PageRange(0, 0) });
}Example 8
| Project: Android-Cookbook-Examples-master File: MainActivity.java View source code |
public void run() {
// Create a shiny new (but blank) PDF document in memory
// We want it to optionally be printable, so add PrintAttributes
// and use a PrintedPdfDocument. Simpler: new PdfDocument().
PrintAttributes printAttrs = new PrintAttributes.Builder().setColorMode(PrintAttributes.COLOR_MODE_COLOR).setMediaSize(PrintAttributes.MediaSize.NA_LETTER).setResolution(new Resolution("zooey", PRINT_SERVICE, 300, 300)).setMinMargins(Margins.NO_MARGINS).build();
PdfDocument document = new PrintedPdfDocument(this, printAttrs);
// crate a page description
PageInfo pageInfo = new PageInfo.Builder(300, 300, 1).create();
// create a new page from the PageInfo
Page page = document.startPage(pageInfo);
// repaint the user's text into the page
View content = findViewById(R.id.textArea);
content.draw(page.getCanvas());
// do final processing of the page
document.finishPage(page);
// accept a String/CharSequence. Meh.
try {
File pdfDirPath = new File(getFilesDir(), "pdfs");
pdfDirPath.mkdirs();
File file = new File(pdfDirPath, "pdfsend.pdf");
Uri contentUri = FileProvider.getUriForFile(this, "com.example.fileprovider", file);
os = new FileOutputStream(file);
document.writeTo(os);
document.close();
os.close();
shareDocument(contentUri);
} catch (IOException e) {
throw new RuntimeException("Error generating file", e);
}
}