IText - Generating PDF with Chinese characters (Chinese Simplified)

前端 未结 2 1762
萌比男神i
萌比男神i 2021-01-28 04:31

I am using iText to generate some PDFs, these pdfs have some Chinese characters (Simplified Chinese - GB2312), however I am unable to generate a pdf with these characters.

相关标签:
2条回答
  • 2021-01-28 04:40

    You have the iText jar in your CLASSPATH, but you forgot to add the (correct) itext-asian.jar.

    Please download version 2.3 of the extra jars ZIP-file that is available here: http://sourceforge.net/projects/itext/files/extrajars/

    This jar contains metrics for Chinese glyphs. Such a font will never be embedded. When you open a document using such a font in Adobe Reader, you may be asked to install an extra font pack.

    0 讨论(0)
  • 2021-01-28 04:48

    The solution adopted:

    private static final String PATH_FONT_ARIALUNI = "C:\\Windows\\Fonts\\arialuni.ttf";
          private static final String PATH_FONT_COUR = "C:\\Windows\\Fonts\\cour.ttf";
    
    
    
           // FOR Chinese
           BaseFont baseFont = BaseFont.createFont(PATH_FONT_ARIALUNI, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
           Font font = new Font(baseFont, 6.8f);
    
           BaseFont baseFontNormal = BaseFont.createFont(PATH_FONT_COUR, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
           Font fontNormal = new Font(baseFontNormal, 6.8f);
    
           Paragraph par = new Paragraph();
           par.setLeading(9);
    
           char[] aa = line.toCharArray();
           boolean isLastChineseChar = false;
    
           System.out.println(line);
    
           StringBuilder newLine = new StringBuilder();
           for (int j = 0; j < line.length(); j++) {
    
               if((Character.UnicodeBlock.of(aa[j]) == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS)){
                   if(!isLastChineseChar) {
                       par.add(new Phrase(newLine.toString(), fontNormal));
                       newLine.delete(0, newLine.length());
                   }
                   newLine.append(aa[j]);
                   isLastChineseChar = true;
                   /*System.out.println("Is CHINESE: " + aa[j]);*/
               } else {
                   if(isLastChineseChar) {
                       par.add(new Phrase(newLine.toString(), font));
                       newLine.delete(0, newLine.length());
                       isLastChineseChar = false;
                   }
                   newLine.append(aa[j]);
                   /*System.out.println("NOT IS CHINESE: " + aa[j]);*/
               }
           }
    
           if(isLastChineseChar){
               par.add(new Phrase(newLine.toString(), font));
           } else {
               par.add(new Phrase(newLine.toString(), fontNormal));
           }       
    
           if(line.contains(BREAK_PAGE)) {
              document.newPage();
           }
    
           par.setAlignment(Element.ALIGN_LEFT);
           document.add(par);
    
    0 讨论(0)
提交回复
热议问题