如何将可滚动布局转换为多页pdf。我已经在一个pdf页面中隐蔽了布局,但是并没有占用多页

时间:2018-12-11 12:34:47

标签: android

如何将可滚动布局转换为多页pdf。我已经在单个pdf页面中隐蔽了布局,但没有占用多页

///此方法先将隐式布局转换为位图,然后转换为pdf。

公共位图loadBitmapFromView(视图v,整数宽度,整数高度){

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

    Canvas c = new Canvas(b);
    v.draw(c);

    return b;
}

//使用此方法创建pdf

private void createPdf() {
  WindowManager wm = (WindowManager) 
    getSystemService(Context.WINDOW_SERVICE);
    //  Display display = wm.getDefaultDisplay();
    DisplayMetrics displaymetrics = new DisplayMetrics();
    this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
    float hight = displaymetrics.heightPixels;
    float width = displaymetrics.widthPixels;

    int convertHighet = (int) hight, convertWidth = (int) width;
    PdfDocument document = new PdfDocument();
    PdfDocument.PageInfo pageInfo = new 
   PdfDocument.PageInfo.Builder(convertWidth, convertHighet, 2).create();
    PdfDocument.Page page = document.startPage(pageInfo);

    Canvas canvas = page.getCanvas();

    Paint paint = new Paint();
    canvas.drawPaint(paint);

    bitmap = Bitmap.createScaledBitmap(bitmap, convertWidth, convertHighet, 
  true);

    paint.setColor(Color.BLUE);
    canvas.drawBitmap(bitmap, 0, 0, null);
    document.finishPage(page);

    // write the document content
    String targetPdf = "/sdcard/pdffromScroll.pdf";
    File filePath;
    filePath = new File(targetPdf);
    try {
        document.writeTo(new FileOutputStream(filePath));

    } catch (IOException e) {
        e.printStackTrace();
        Toast.makeText(this, "Something wrong: " + e.toString(), Toast.LENGTH_LONG).show();
    }

   document.close()

    openGeneratedPDF();

}

//打开生成的pdf

private void openGeneratedPDF() {
    File file = new File("/sdcard/pdffromScroll.pdf");
    if (file.exists()) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri uri = Uri.fromFile(file);
        intent.setDataAndType(uri, "application/pdf");
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        try {
            startActivity(intent);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(NewsFullDescription.this, "No Application available to view pdf", Toast.LENGTH_LONG).show();
        }
    }
}

0 个答案:

没有答案