You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio中如何将本地HTML文件转换为PDF格式

Android 本地HTML转PDF实现方案

采用Android原生PrintManager框架配合WebView实现,无需引入第三方依赖,支持Android 4.4及以上全版本,不存在过时问题。

实现代码

首先在你现有HTML保存逻辑的基础上,新增如下转换方法:

private void convertHtmlToPdf(String htmlFilePath, String outputPdfPath) {
    WebView webView = new WebView(this);
    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
            PrintDocumentAdapter printAdapter = webView.createPrintDocumentAdapter("outputPdf");
            
            PrintAttributes printAttrs = new PrintAttributes.Builder()
                    .setMediaSize(PrintAttributes.MediaSize.ISO_A4)
                    .setResolution(new PrintAttributes.Resolution("pdf_res", "PDF", 600, 600))
                    .setMinMargins(PrintAttributes.Margins.NO_MARGINS)
                    .build();

            // 方式1:调用系统打印UI,用户可手动选择保存为PDF或连接打印机
            printManager.print("PDF生成任务", printAdapter, printAttrs);

            // 方式2:无需用户交互,直接后台输出到指定路径,取消注释即可使用
            /*
            CancellationSignal cancelSignal = new CancellationSignal();
            printAdapter.onLayout(printAttrs, printAttrs, cancelSignal, new PrintDocumentAdapter.LayoutResultCallback() {}, null);
            
            try {
                ParcelFileDescriptor pfd = ParcelFileDescriptor.open(
                    new File(outputPdfPath),
                    ParcelFileDescriptor.MODE_READ_WRITE | ParcelFileDescriptor.MODE_CREATE | ParcelFileDescriptor.MODE_TRUNCATE
                );
                printAdapter.onWrite(new PageRange[]{PageRange.ALL_PAGES}, pfd, cancelSignal, new PrintDocumentAdapter.WriteResultCallback() {
                    @Override
                    public void onWriteFinished(@NonNull PageRange[] pages) {
                        super.onWriteFinished(pages);
                        try {
                            pfd.close();
                            Toast.makeText(getApplicationContext(), "PDF已保存至:" + outputPdfPath, Toast.LENGTH_SHORT).show();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            */
        }
    });
    webView.loadUrl("file://" + htmlFilePath);
}

在你原有保存HTML成功的逻辑处调用即可:

// 原有保存HTML成功后的代码
Log.e(TAG, "File Save : " + filePath.getPath());
Toast.makeText(this,"Saved in "+filePath.getPath(),Toast.LENGTH_SHORT).show();
// 新增调用转换逻辑
String pdfPath = directory_path + "/myConvertedFile.pdf";
convertHtmlToPdf(filePath.getPath(), pdfPath);

注意事项

  • 你当前使用getExternalFilesDir存储文件属于应用私有目录,无需申请额外的存储权限,适配所有Android版本
  • 如果HTML中包含本地图片、CSS等资源,需要将资源和HTML文件放在同一目录下,WebView即可正常渲染
  • 若生成的PDF排版不符合预期,可以调整PrintAttributes中的页面尺寸、边距参数,或者在HTML代码中加入打印专用的CSS样式

内容的提问来源于stack exchange,提问作者Awais Gondal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 20:45:04