itext utf8 html到pdf android

时间:2018-08-08 04:54:26

标签: android pdf itext

我正在尝试将一些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

1 个答案:

答案 0 :(得分:0)

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