How to print utf-8 strings into a pdf file useing libharu

117 Views Asked by At

I am trying to write a PDF document with Chinese strings. The strings are available in the source code encoded as utf-8.

When I compile and run the below (on linux Debian) I get an error of "ERROR: error_no=1028, detail_no=0".

If I change the font selection from "SimSun" to "Helvetica", there are no errors. (and obviously no Chinese in the output since that font does not include those characters.)

I suspect I am missing something simple, but I don't know what it is.

I have tried to do this from the examples I found (see the code below), but I did not see one where they printed Chinese and had utf-8 strings in the source code.

    #include <stdio.h>
    #include <setjmp.h>
    #include "hpdf.h"

    jmp_buf env;

    void error_handler (HPDF_STATUS   error_no,
                   HPDF_STATUS   detail_no,
                   void         *user_data)
    {
        printf ("ERROR: error_no=%04X, detail_no=%u\n", (HPDF_UINT)error_no, (HPDF_UINT)detail_no);
        longjmp(env, 1);
    }

    int main (int argc, char **argv)
    {
        HPDF_Doc pdf = HPDF_New (error_handler, NULL);
        if (!pdf) {
            printf ("error: cannot create PdfDoc object\n");
            return 1;
        }

        if (setjmp(env)) {
            HPDF_Free (pdf);
            return 1;
        }

        HPDF_UseUTFEncodings(pdf);
        HPDF_SetCurrentEncoder(pdf, "UTF-8");
        HPDF_UseCNSFonts (pdf);
        HPDF_Page page = HPDF_AddPage (pdf);

        HPDF_REAL height = HPDF_Page_GetHeight (page);
        HPDF_REAL width = HPDF_Page_GetWidth (page);

        HPDF_Font def_font = HPDF_GetFont (pdf, "SimSun", NULL);
        //HPDF_Font def_font = HPDF_GetFont (pdf, "Helvetica", NULL);
        HPDF_Page_SetFontAndSize (page, def_font, 24);

        //const char* text = "Hello World!";
        const char* text = "Hello: 警告:温度控制已禁用。";
        HPDF_REAL tw = HPDF_Page_TextWidth (page, text);
        HPDF_Page_BeginText (page);
        HPDF_Page_TextOut (page, (width - tw) / 2, height - 50, text);
        HPDF_Page_EndText (page);

        HPDF_SaveToFile (pdf, "a.out.pdf");
        HPDF_Free (pdf);

        return 0;
    }

0

There are 0 best solutions below