【问题标题】:Itext utf8 html to pdf androidItext utf8 html 到 pdf android
【发布时间】:2018-08-08 04:54:26
【问题描述】:

我正在尝试将一些 html 导出为 pdf 文件。我正在使用 iText。我的 html 实际上有孟加拉语 (UTF-8) 字符,这些字符要么未显示在 pdf 中,要么显示为 ?????

这是我的代码:

private void pdfCreate (String filePath) {

        try {

            String path = article.getTitle() + ".pdf";


            String rootPath = Environment.getExternalStorageDirectory()
                    .getAbsolutePath() + "/mukti/";
            File root = new File(rootPath);
            if (!root.exists()) {
                root.mkdirs();
            }
            File f = new File(rootPath + path);
            if (f.exists()) {
                f.delete();
            }

            f.createNewFile();

            String d1 = "<html><head></head><body style=\"font-family:Kalpurush; color: red; background: green;\"> 2546654 ০১৩ সালে ক্লেইনার পার্কিন্সের এক জরিপ অনুযায়ী প্রতিদিন একজন মানুষ গড়ে ১০০-১৫০ বার তার মোবাইল ফোন চেক করতো। ৩ </body></html>";


            OutputStream myFile = new FileOutputStream(f);
            Document document = new Document();

            document.addCreationDate();
            document.setPageSize(PageSize.A4);
            document.setMargins(36, 36, 36, 36);
            document.setMarginMirroring(true);


            PdfWriter writer = PdfWriter.getInstance(document, myFile);
            document.open();

            XMLWorkerHelper worker = XMLWorkerHelper.getInstance();

            InputStream is;

            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                is = new ByteArrayInputStream(d1.getBytes(StandardCharsets.UTF_8));
            } else
                is = new ByteArrayInputStream(d1.getBytes("UTF-8"));

            String FONT = "assets/fonts/KONGO.ttf";
            XMLWorkerFontProvider fontImp = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
            fontImp.register(FONT);


            worker.parseXHtml(writer, document, is, Charset.forName("UTF-8"), fontImp);

            document.close();
            myFile.close();
            System.out.println("Done.");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

我已经尝试过这个答案,但没有一个有效

Things i tried 1

Things i tried 2

我的输出 PDF:

https://drive.google.com/file/d/17L-cbtKQE5AZjQFD4HeqRPjh83FQiF4I/view?usp=sharing

【问题讨论】:

    标签: android pdf itext


    【解决方案1】:

    看来我的代码运行良好。是 html 正文中的字体系列名称拼写不正确。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-07
      • 2013-02-22
      • 2021-08-08
      • 2022-07-31
      • 2019-09-27
      • 2015-10-13
      • 1970-01-01
      相关资源
      最近更新 更多