android – iText libs – doesn't show Cyrillic(Russian) symbols-ThrowExceptions

Exception or error:

I’ve already spent a few days, what am I doing wrong ?. I just can not get Russian characters out. Tried all the code above – it did not help. Below I quote my code with different options. Help me please.

The library is connected as follows

dependencies {

    implementation 'com.itextpdf:itextpdf:5.5.12'
}

Code ToPdfActivity.java

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.IOException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;

public class ToPdfActivity extends AppCompatActivity {

private static final String TAG = "PdfCreatorActivity";

private Button mCreateButton;
private File pdfFile;
EditText nameFile;


final private int REQUEST_CODE_ASK_PERMISSIONS = 111;
public static final String ENCODING = "cp1251";
File file;
BaseFont bf,times;
Font f_title;
Font f_text;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_to_pdf);


    nameFile = (EditText) findViewById(R.id.nameFile);
    mCreateButton = (Button) findViewById(R.id.button_create);


    Intent intent = getIntent();
    anglRoofView.setText(intent.getStringExtra("stepRafterRoof"));
    squareRoofView.setText(intent.getStringExtra("numbSerLat"));
    intent.getStringExtra("numbStepLat");
    intent.getStringExtra("numbBrus");

    mCreateButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (anglRoofView.getText().toString().isEmpty()){
                anglRoofView.setError("Body is empty");
                anglRoofView.requestFocus();
                return;
            }
            try {
                createPdfWrapper();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (DocumentException e) {
                e.printStackTrace();
            }
        }
    });

}
private void createPdfWrapper() throws FileNotFoundException,DocumentException{

    int hasWriteStoragePermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    if (hasWriteStoragePermission != PackageManager.PERMISSION_GRANTED) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!shouldShowRequestPermissionRationale(Manifest.permission.WRITE_CONTACTS)) {
                showMessageOKCancel("You need to allow access to Storage",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                    requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                            REQUEST_CODE_ASK_PERMISSIONS);
                                }
                            }
                        });
                return;
            }

            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    REQUEST_CODE_ASK_PERMISSIONS);
        }
        return;
    }else {
        try {
            createPdf();                
    } catch (IOException e) {
            e.printStackTrace();

    } catch (DocumentException e) {
        e.printStackTrace();
    }

    }
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
        case REQUEST_CODE_ASK_PERMISSIONS:
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
                try {
                    createPdfWrapper();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (DocumentException e) {
                    e.printStackTrace();
                }
            } else {
                // Permission Denied
                Toast.makeText(this, "WRITE_EXTERNAL Permission Denied", Toast.LENGTH_SHORT)
                        .show();
            }
            break;
        default:
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
    new AlertDialog.Builder(this)
            .setMessage(message)
            .setPositiveButton("OK", okListener)
            .setNegativeButton("Cancel", null)
            .create()
            .show();
}

private void createPdf() throws DocumentException, IOException {
    setFont();
    setFontT();
    try{


    File docsFolder = new File(Environment.getExternalStorageDirectory() + "/Documents");
    if (!docsFolder.exists()) {
        docsFolder.mkdir();
        Log.i(TAG, "Created a new directory for PDF");
    }

    pdfFile = new File(docsFolder.getAbsolutePath(),nameFile.getText().toString()+".pdf");
    OutputStream output = new FileOutputStream(pdfFile);
    Document document = new Document(PageSize.A4);
    PdfWriter writer = PdfWriter.getInstance(document, output);
    document.open();

    FontFactory.register(System.getProperty("file.separator")+"resources"+System.getProperty("file.separator")+"fonts"+System.getProperty("file.separator")+"arial.‌​ttf", "my_bold_font");

    Font fonts1 = FontFactory.getFont("my_bold_font", "CP1251",BaseFont.EMBEDDED, 10);

    Font bfComic =  new Font(Font.FontFamily.HELVETICA, 24, Font.NORMAL, BaseColor.BLACK);

    Font f1 = FontFactory.getFont("/fonts/arial.ttf", "CP1251", true);
    Font f2 = FontFactory.getFont("my_bold_font", FontFactory.TIMES, true);
    Font font1 = FontFactory.getFont("my_bold_font", BaseFont.IDENTITY_H, true);
    Font font = FontFactory.getFont("my_bold_font", "CP1251", BaseFont.EMBEDDED);


        Paragraph title = new Paragraph();
        title.setAlignment(Element.ALIGN_CENTER);
        title.setFont(f_title);
        title.add("Счет фактура hhklklke");

        document.add(title);

        document.add(new Paragraph(String.format("Просто текст", f1)));
        document.add(new Paragraph(String.format(anglRoofView.getText().toString(), f1)));
        document.add(new Paragraph(String.format("Просто текст", f2)));
        document.add(new Paragraph(String.format(squareRoofView.getText().toString(), f1)));
        document.add(new Paragraph(String.format("Просто текст", fonts1)));
        document.add(new Paragraph(String.format("Просто текст",f_title)));
        //document.add(new Paragraph(String.format("Просто текст",bfComic)));
        document.add(new Paragraph("Jjjвпкпккпdfhwh9iuкпп h9w8e", font1));
        document.add(new Paragraph("Jjjвпкпккпdfhwh9iuкпп h9w8e", font));

        document.add(create_table());

        PdfPTable table = new PdfPTable(4);

        PdfPCell cell;

        cell = new PdfPCell(new Phrase("Объединение колонок 3", new Font(times,14)));
        cell.setColspan(3);
        table.addCell(cell);

        cell = new PdfPCell(new Phrase("Объединение ячеек строк 3", new Font(times,14)));
        cell.setRowspan(3);
        table.addCell(cell);

        cell = new PdfPCell(new Phrase("Объединение строк 2", new Font(times,14)));
        cell.setRowspan(2);
        table.addCell(cell);

        table.addCell("1; 1");
        table.addCell("1; 2");
        table.addCell("2; 1");
        table.addCell("2; 2");
        table.addCell("2; 3");
        document.add(table);

        Font fon = FontFactory.getFont("resources/fonts/FreeSans.ttf", "Cp1251", BaseFont.EMBEDDED);
        document.add(new Paragraph("\u041e\u0442\u043a\u0443\u0434\u0430 \u0442\u044b?", fon));
        document.add(new Paragraph("\u0423\u0432\u0438\u0434\u0438\u043c\u0441\u044f \u0432 \u043d\u0435\u043c\u043d\u043e\u0433\u043e. \u0423\u0432\u0438\u0434\u0438\u043c\u0441\u044f.", fon));
        document.add(new Paragraph("\u041f\u043e\u0437\u0432\u043e\u043b\u044c\u0442\u0435 \u043c\u043d\u0435 \u043f\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u0438\u0442\u044c\u0441\u044f.", font));
        document.add(new Paragraph("\u042d\u0442\u043e \u0441\u0442\u0443\u0434\u0435\u043d\u0442.", fon));
        document.add(new Paragraph("\u0425\u043e\u0440\u043e\u0448\u043e?", font));
        document.add(new Paragraph("\u041e\u043d \u0438\u043d\u0436\u0435\u043d\u0435\u0440. \u041e\u043d\u0430 \u0434\u043e\u043a\u0442\u043e\u0440.", f_text));
        document.add(new Paragraph("\u042d\u0442\u043e \u043e\u043a\u043d\u043e.", font));
        document.add(new Paragraph("\u041f\u043e\u0432\u0442\u043e\u0440\u0438\u0442\u0435, \u043f\u043e\u0436\u0430\u043b\u0443\u0439\u0441\u0442\u0430.", font1));

        document.close();

        previewPdf();
        Intent intent = new Intent();
        setResult(RESULT_OK, intent);
        finish();

    }catch(Exception ex){
        ex.printStackTrace();
    }

}
public void setFont() throws DocumentException, IOException{
    try{
        bf = BaseFont.createFont("resources/fonts/FreeSans.ttf", "CP1251" , BaseFont.EMBEDDED);
        f_title = new Font(bf, 18 );
        f_text = new Font(bf);
    }catch(Exception ex){
        ex.printStackTrace();
    }
}
public void setFontT() throws DocumentException, IOException{
    try{
        BaseFont times =
                BaseFont.createFont("resources/fonts/times.ttf","cp1251",BaseFont.EMBEDDED);
        f_title = new Font(times, 18 );
        f_text = new Font(times);
    }catch(Exception ex){
        ex.printStackTrace();
    }
}
public PdfPTable create_table() throws DocumentException{
    PdfPTable table = new PdfPTable(2);
    table.setWidthPercentage(100);
    table.setSpacingBefore(5f);

    PdfPCell cell;
    Phrase ph = new Phrase();
    ph.setFont(f_text);
    ph = new Phrase("Номерhhhhfdf");


    cell = new PdfPCell(ph);
    table.addCell(cell);
    table.addCell("Nuber");

    return table;
}
private void previewPdf() {

    PackageManager packageManager = getPackageManager();
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setType("application/pdf");
    List list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
    if (list.size() >= 0) {

        intent.setData(Uri.fromFile(pdfFile));
        Intent j = Intent.createChooser(intent, "Выберите приложения для открытия PDF файла:");
        startActivity(j);
    }else{
        Toast.makeText(this,"Download a PDF Viewer to see the generated PDF",Toast.LENGTH_SHORT).show();
    }
}

Only words in English are displayed correctly
enter image description here

How to solve:

At last. I result a variant how to deduce Russian symbols.

File | New | Folder | Assets Folder
create new folder /fonts

We copy the file arial.ttf or times.ttf, we paste into the created folder /assets/fonts

In the project we write the following:

public static final String FONT = "/assets/fonts/arial.ttf";

BaseFont bf=BaseFont.createFont(FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font font=new Font(bf,30,Font.NORMAL);
document.open();
document.add(new Paragraph("Привет",font));
document.close();

All works on hurray

###

For iText 7:

Document doc = new Document(new PdfDocument(new PdfWriter("output.pdf")));

String FONT_FILENAME = "./src/main/resources/arial.ttf";
PdfFont font = PdfFontFactory.createFont(FONT_FILENAME, PdfEncodings.IDENTITY_H);

doc.setFont(font);

// Font can be applied to other elements, e.g.
// new Paragraph("Some text").setFont(font);
// new Table().setFont(font);

where arial.ttf is font file (to be downloaded / copied).

More examples: https://itextpdf.com/en/resources/examples/itext-7/language-specific-examples

Leave a Reply

Your email address will not be published. Required fields are marked *