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

使用iText 5.5.13.2生成PDF可查看但分享时为0字节损坏怎么办

问题根因及解决方案

核心问题1:文件创建逻辑错误

你的文件存在判断逻辑完全写反了,原代码中只有文件已经存在时才会尝试创建新文件,而createNewFile()本身的作用就是「仅当文件不存在时才创建新文件」,这段逻辑完全无效,极端情况下会导致文件创建失败、写入异常。

核心问题2:安卓版本适配问题(导致分享时0字节的最主要原因)

安卓7.0(API 24)及以上版本禁止了应用之间直接使用Uri.fromFile()共享私有目录文件,接收分享的第三方应用没有权限访问你应用专属目录下的users.pdf,因此会读取到0字节的空文件,弹出损坏提示。你自己的应用有权限访问该文件,所以本地打开正常。

额外隐患:资源关闭逻辑不严谨

如果PDF生成过程中抛出异常,会导致document.close()无法执行,PDF的IO流没有正常关闭,也会导致文件写入不完整。


修复步骤

1. 修正文件创建逻辑

将ConvertToPdf()方法中的文件创建判断修改为:

File file = new File(path);
// 改为文件不存在时才创建
if(!file.exists()){
    try{
        file.createNewFile();
    }catch (IOException e){
        e.printStackTrace();
    }
}

2. 适配FileProvider实现文件分享

步骤1:在AndroidManifest.xml中注册FileProvider

<application>
    ...
    <provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="${applicationId}.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
    </provider>
</application>

步骤2:新建res/xml/file_paths.xml配置共享目录

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <!-- 对应你使用的getExternalFilesDir目录 -->
    <external-files-path
        name="pdf_share"
        path="." />
</paths>

步骤3:修改分享逻辑

public void onsharePDF() {
    String path = getExternalFilesDir(null).getAbsolutePath().toString()+"/users.pdf";
    File file = new File(path);
    if(file.exists() && file.length() > 0){
        Intent share = new Intent();
        share.setAction(Intent.ACTION_SEND);
        // 替换Uri.fromFile为FileProvider获取Uri
        Uri pdfUri = FileProvider.getUriForFile(this, getPackageName()+".fileprovider", file);
        share.putExtra(Intent.EXTRA_STREAM, pdfUri);
        // 给接收方授予读取权限
        share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        share.setType("application/pdf");
        startActivity(share);
    }
}

3. 优化PDF生成的异常处理

用try-finally确保document一定会被关闭:

Document document = new Document(PageSize.A4);
try {
    PdfWriter.getInstance(document, new FileOutputStream(file.getAbsoluteFile()));
    document.open();
    // 原有写入内容的逻辑
    Font font = new Font(Font.FontFamily.COURIER, 14);
    Font font_title = new Font(Font.FontFamily.COURIER, 24);
    ...
    document.add(img);
    document.add(paragraph);
} catch (Exception e) {
    e.printStackTrace();
} finally {
    // 确保无论是否发生异常都会关闭document,完成文件写入
    if(document.isOpen()){
        document.close();
    }
}

内容的提问来源于stack exchange,提问作者Yann Chevalier

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 15:36:03