Создание и отображение отчетов в формате PDF во внутренней памяти Android - PullRequest
0 голосов
/ 11 мая 2019

Я делаю приложение для Android, в котором я должен делать отчеты в формате PDF.Данные для этих отчетов поступают из базы данных SQLite.Страницы PDF создаются правильно, но у меня проблема с их отображением.PDF не отображается.Я хочу, чтобы страница PDF отображалась сама собой после ее создания.Вот код создания отчетов в формате PDF:

 public void savePDF(){

    Document mDoc = new Document();
    fileName = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.getDefault()).format(System.currentTimeMillis());
    filePath = Environment.getExternalStorageDirectory() + "/Project Manager/" + "Project Report/" ;
    try{
        File dir = new File(filePath);
        if (!dir.exists())
            dir.mkdirs();

        file = new File(dir, nameforR + "_" +fileName+".pdf");
        FileOutputStream fOut = new FileOutputStream(file);
        PdfWriter.getInstance(mDoc,fOut);
        mDoc.open();

        mDoc.addTitle("Project Manager");
        mDoc.addSubject("Project Report");
        mDoc.addKeywords("Projects");
        mDoc.addAuthor("Fahad");
        mDoc.addCreator("Fahad");

            Paragraph preface = new Paragraph();
            Paragraph repTitle = new Paragraph("Project Manager", catFont);
            repTitle.setAlignment(Element.ALIGN_CENTER);
            preface.add(repTitle);

            Paragraph repTitlepowered = new Paragraph("PDF Reports", smallBold);
            repTitlepowered.setAlignment(Element.ALIGN_CENTER);
            preface.add(repTitlepowered);

            Paragraph emptyL = new Paragraph("\n");
            preface.add(emptyL);

            Paragraph reportTitle = new Paragraph(nameforR, subFont);
            reportTitle.setAlignment(Element.ALIGN_CENTER);
            preface.add(reportTitle);
            mDoc.add(preface);
            Paragraph emptyLine = new Paragraph("\n");
            mDoc.add(emptyLine);

            PdfPTable table = new PdfPTable(3);
            table.setWidthPercentage(70);
            table.setSpacingAfter(10);}

        mDoc.add(Chunk.NEWLINE);
        mDoc.add(tableDeductions);

            mDoc.close();
            showPDf();
}

Код для отображения отчетов:

 private void showPDF(){
    AssetManager assetManager = getAssets();
    InputStream in = null;
    OutputStream out = null;
    File file = new File(getFilesDir() ,fileName + ".pdf");
    try
    {
        in = assetManager.open(fileName + ".pdf");
        out = this.openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);

        copyFile(in, out);
        in.close();
        in = null;
        out.flush();
        out.close();
        out = null;
    }
    catch (Exception e)
    {
        Log.e("tag", e.getMessage());
    }

    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.fromFile(file), "application/pdf");
    intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
    startActivity(intent);
}

private void copyFile(InputStream in, OutputStream out) throws IOException
{
    byte[] buffer = new byte[1024];
    int read;
    while ((read = in.read(buffer)) != -1)
    {
        out.write(buffer, 0, read);
    }
}

Ответы [ 2 ]

0 голосов
/ 11 мая 2019

Открыть pdf с pdfReader попробуйте

  // before open pdf make sure any pdfReader app exist on your device
   try {
        File file=new File("paste here your pdf path");
        Uri path=Uri.fromFile(file);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(path, "application/pdf");
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }catch (ActivityNotFoundException e){
        e.printStackTrace();
    }
    }
0 голосов
/ 11 мая 2019

Для просмотра PDF в вашем собственном приложении, попробуйте это

// First create activity

// activity xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".activity.LoadPdfActivity">

<android.support.v4.view.ViewPager
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:id="@+id/viewPager">
</android.support.v4.view.ViewPager>

</LinearLayout>

public class LoadPdfActivity extends AppCompatActivity {
private ViewPager viewPager;
private PdfPagerAdapter pdfAdapter;
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_load_pdf);
    viewPager=(ViewPager)findViewById(R.id.viewPager);
    String pdfPath = "paste here your pdf path";
    pdfAdapter=new PdfPagerAdapter(this,pdfPath,2.0f);
    viewPager.setAdapter(pdfAdapter);
}

}

// класс адаптера viewPage

public class PdfPagerAdapter extends PagerAdapter {
private Context context;
private String path;
private float renderQuality;
protected LayoutInflater inflater;
int width = 0;
int height = 0;
protected PdfRenderer renderer;

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public PdfPagerAdapter(Context context, String path, float renderQuality){
    this.context=context;
    this.path=path;
    this.renderQuality=renderQuality;
    init();
}

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void init(){
    try {
        renderer = new PdfRenderer(getSeekableFileDescriptor(path));
        inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        PdfRenderer.Page samplePage = getPDFPage(0);
        width = (int) (samplePage.getWidth() * renderQuality);
        height = (int) (samplePage.getHeight() * renderQuality);
        samplePage.close();

    } catch (IOException e) {
        e.printStackTrace();
        Log.e("PDFPagerAdapter", e.getMessage());
    }
}

@SuppressWarnings("NewApi")
protected PdfRenderer.Page getPDFPage(int position) {
    return renderer.openPage(position);
}


private ParcelFileDescriptor getSeekableFileDescriptor(String path) throws FileNotFoundException {
    ParcelFileDescriptor pfd = null;
    File pdfCopy = new File(path);
    if (pdfCopy.exists()) {
        pfd = ParcelFileDescriptor.open(pdfCopy, ParcelFileDescriptor.MODE_READ_ONLY);
        return pfd;
    }
    return pfd;
}

@SuppressLint("NewApi")
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
        View v = inflater.inflate(R.layout.img_full_view, container, false);
        ImageView iv = (ImageView) v.findViewById(R.id.imageView);

        if (renderer == null || getCount() < position) {
            return v;
        }

        PdfRenderer.Page page = getPDFPage(position);

        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

        page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
        page.close();

        iv.setImageBitmap(bitmap);
        ((ViewPager) container).addView(v, 0);

        return v;
}

@SuppressLint("NewApi")
@Override
public int getCount() {
    return renderer != null ? renderer.getPageCount() : 0;
}

@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
    return view==((View) o);
}

@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
    container.removeView((View) object);
}

}


// viewPager adapter xml file

   <LinearLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:gravity="center"
   android:orientation="vertical">
  <ImageView
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:id="@+id/imageView"/>
 </LinearLayout>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...