2014-10-16 4 views
1

У меня есть класс, чтобы открыть пустой лист символов (для LARP), хранящийся в моих исходных ресурсах, а затем добавить некоторые значения в пустые поля с помощью iText. PDF-файл хранится в /data/data/package/files просто отлично, но когда я пытаюсь использовать метод OpenPDF, я получаю ошибку EACCES (permission denied). Если я попытаюсь использовать adb для экспорта на свой компьютер, я могу без проблем открыть его в PDF-редакторах/редакторах.Невозможно открыть PDF в приложениях для просмотра PDF

Все еще довольно новичок в разработке Android, поэтому я понятия не имею, почему я получаю отказ от разрешения.

imports... 

/** 
* Created by Matt on 10/15/2014. 
*/ 
public class SheetBuilder { 

    private final String LOGTAG = getClass().getName(); 

    private Context context; 
    private InputStream inputStream; 
    private OutputStream outputStream = null; 
    private PdfReader reader = null; 
    private Document document; 
    private PdfWriter writer = null; 
    private String outputFileName; 
    private PdfContentByte canvas; 

    private int alignment = Element.ALIGN_LEFT; 

    public SheetBuilder(Context context, int sourceFile, String outputFileName) { 
     this.outputFileName = outputFileName.replace(".pdf", "") + ".pdf"; 
     this.context = context; 

     inputStream = context.getResources().openRawResource(sourceFile); 
     try { 
      reader = new PdfReader(inputStream); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     try { 
      outputStream = context.openFileOutput(this.outputFileName, context.MODE_PRIVATE); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

     document = new Document(reader.getPageSize(1)); 
     try { 
      writer = PdfWriter.getInstance(document, outputStream); 
     } catch (DocumentException e) { 
      e.printStackTrace(); 
     } 
     document.open(); 
     canvas = writer.getDirectContent(); 
    } 

    public void OpenPDF() { 
     ContextWrapper cw = new ContextWrapper(context); 
     File path = cw.getFilesDir(); 
     File pdfFile = new File(path + "/" + outputFileName); 
     if(pdfFile.exists()) 
     { 
      Log.i(LOGTAG, "Found " + outputFileName); 

      Uri uriPath = Uri.fromFile(pdfFile); 
      Intent pdfIntent = new Intent(Intent.ACTION_VIEW); 
      pdfIntent.setDataAndType(uriPath, "application/pdf"); 
      pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

      try { 
       context.startActivity(pdfIntent); 
      } catch (ActivityNotFoundException e) { 
       Toast.makeText(context, "No application available to view PDF", Toast.LENGTH_LONG).show(); 
      } 
     } 
    } 

    public void ImportPage(int PageNumber) { 
     if(PageNumber == 0) PageNumber = 1; 
     PdfImportedPage page = writer.getImportedPage(reader, PageNumber); 
     document.newPage(); 
     canvas.addTemplate(page, 0, 0); 
    } 

    public void setAlignment(int Alignment) { 
     this.alignment = Alignment; 
    } 

    public void setAlignment() { 
     this.alignment = Element.ALIGN_LEFT; 
    } 

    public void AddBasicPhrase(String phrase, float x, float y, float rotation) { 
     Phrase p = new Phrase(phrase); 
     ColumnText.showTextAligned(canvas, alignment, p, x, y, rotation); 
    } 

    public void AddBasicPhrase(String phrase, float x, float y) { 
     AddBasicPhrase(phrase, x, y, 0); 
    } 

    public void Close() { 
     document.close(); 

     if (outputStream != null) { 
      try { 
       outputStream.flush(); 
       outputStream.close(); 
       inputStream.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

} 
+0

Я уверен, что на это был дан ответ раньше, но когда я искал его, я продолжал получать вещи, которые не отвечали на мой вопрос, и я не видел того, что было выше. И те, которые, казалось, отвечали на мой вопрос, оставляли мне другие ошибки, пока я не понял, как заставить его работать. –

ответ

1

Нашел свое решение. Изменения, отмеченные комментариями ниже. Поправьте меня, если я сделаю что-то, чего я не должен. Обнаруженное хранилище файлов «External vs Internal» было моей проблемой.

/** 
* Created by Matt on 10/15/2014. 
*/ 
public class SheetBuilder { 

    private final String LOGTAG = getClass().getName(); 

    private Context context; 
    private InputStream inputStream; 
    private OutputStream outputStream = null; 
    private PdfReader reader = null; 
    private Document document; 
    private PdfWriter writer = null; 
    private String outputFileName; 
    private PdfContentByte canvas; 

    private int alignment = Element.ALIGN_LEFT; 

    public SheetBuilder(Context context, int sourceFile, String outputFileName) { 
     this.outputFileName = outputFileName.replace(".pdf", "") + ".pdf"; 
     this.context = context; 

     inputStream = context.getResources().openRawResource(sourceFile); 
     try { 
      reader = new PdfReader(inputStream); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     /* Changes From Here */  
     try { 
      File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS); 
      File file = new File(path, this.outputFileName); 
      Log.i("ExternalStorage", file.getAbsolutePath()); 
      path.mkdirs(); 
      outputStream = new FileOutputStream(file); 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     /* To Here */ 

     document = new Document(reader.getPageSize(1)); 
     try { 
      writer = PdfWriter.getInstance(document, outputStream); 
     } catch (DocumentException e) { 
      Log.e("ErrorsAllAround", "Nope!"); 
      e.printStackTrace(); 
     } 
     document.open(); 
     canvas = writer.getDirectContent(); 
    } 

    public void OpenPDF() { 
     /* Changes From Here */ 
     File pdfFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), outputFileName); 
     /* To Here */ 
     if(pdfFile.exists()) 
     { 
      Log.i(LOGTAG, "Found " + pdfFile.getAbsolutePath()); 

      Uri uriPath = Uri.fromFile(pdfFile); 
      Intent pdfIntent = new Intent(Intent.ACTION_VIEW); 
      pdfIntent.setDataAndType(uriPath, "application/pdf"); 
      pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

      try { 
       context.startActivity(pdfIntent); 
      } catch (ActivityNotFoundException e) { 
       Toast.makeText(context, "No application available to view PDF", Toast.LENGTH_LONG).show(); 
      } 
     } 
     else 
     { 
      Log.i(LOGTAG, "File Not Found: " + pdfFile.getAbsolutePath()); 
      Toast.makeText(context, "File Not Found: " + pdfFile.getAbsolutePath(), Toast.LENGTH_LONG).show(); 
     } 
    } 

    public void ImportPage(int PageNumber) { 
     if(PageNumber == 0) PageNumber = 1; 
     PdfImportedPage page = writer.getImportedPage(reader, PageNumber); 
     document.newPage(); 
     canvas.addTemplate(page, 0, 0); 
    } 

    public void setAlignment(int Alignment) { 
     this.alignment = Alignment; 
    } 

    public void setAlignment() { 
     this.alignment = Element.ALIGN_LEFT; 
    } 

    public void AddBasicPhrase(String phrase, float x, float y, float rotation) { 
     Phrase p = new Phrase(phrase); 
     ColumnText.showTextAligned(canvas, alignment, p, x, y, rotation); 
    } 

    public void AddBasicPhrase(String phrase, float x, float y) { 
     AddBasicPhrase(phrase, x, y, 0); 
    } 

    public void Close() { 
     document.close(); 

     if (outputStream != null) { 
      try { 
       outputStream.flush(); 
       outputStream.close(); 
       inputStream.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

} 
Смежные вопросы