Avoid potential negative array index access to cached text.
[LibreOffice.git] / android / source / src / java / org / libreoffice / PDFDocumentAdapter.java
blob2ce167ce3a32f7ea9d3f4e6987e7e12ede45b2ad
1 package org.libreoffice;
3 import android.annotation.TargetApi;
4 import android.content.Context;
5 import android.os.Bundle;
6 import android.os.CancellationSignal;
7 import android.os.ParcelFileDescriptor;
8 import android.print.PageRange;
9 import android.print.PrintAttributes;
10 import android.print.PrintDocumentAdapter;
11 import android.print.PrintDocumentInfo;
13 import java.io.File;
14 import java.io.FileInputStream;
15 import java.io.FileOutputStream;
16 import java.io.IOException;
17 import java.io.InputStream;
18 import java.io.OutputStream;
20 @TargetApi(19)
21 public class PDFDocumentAdapter extends PrintDocumentAdapter{
22 Context mContext;
23 String pdfFile;
25 public PDFDocumentAdapter(Context mContext, String pdfFile) {
26 this.mContext = mContext;
27 this.pdfFile = pdfFile;
30 @Override
31 public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras) {
32 if (cancellationSignal.isCanceled()) {
33 callback.onLayoutCancelled();
35 else {
36 File f = new File(pdfFile);
37 PrintDocumentInfo.Builder builder=
38 new PrintDocumentInfo.Builder(f.getName());
39 builder.setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT)
40 .setPageCount(PrintDocumentInfo.PAGE_COUNT_UNKNOWN)
41 .build();
42 callback.onLayoutFinished(builder.build(),
43 !newAttributes.equals(oldAttributes));
47 @Override
48 public void onWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback) {
49 InputStream in=null;
50 OutputStream out=null;
51 try {
52 File file = new File(pdfFile);
53 in = new FileInputStream(file);
54 out=new FileOutputStream(destination.getFileDescriptor());
56 byte[] buf=new byte[in.available()];
57 int size;
59 while ((size=in.read(buf)) >= 0
60 && !cancellationSignal.isCanceled()) {
61 out.write(buf, 0, size);
64 if (cancellationSignal.isCanceled()) {
65 callback.onWriteCancelled();
67 else {
68 callback.onWriteFinished(new PageRange[] { PageRange.ALL_PAGES });
71 catch (Exception e) {
72 callback.onWriteFailed(e.getMessage());
73 e.printStackTrace();
75 finally {
76 try {
77 in.close();
78 out.close();
80 catch (IOException e) {
81 e.printStackTrace();