Warm tip: This article is reproduced from stackoverflow.com, please click
c# pdf zpl

Using ttf font in Labelary api via c#

发布于 2021-02-07 16:58:10

I am trying to convert existing zpl code into the pdf file using labelary web service. Existing zpl label template uses Consolas.ttf preloaded font. Labelary documentation said that it's possible to use ~DU command. I am trying this c# code to achieve "teststring" label written by Consolas.ttf font.

         byte[] zpl = Encoding.UTF8.GetBytes($@"^xa^CI~DUR:consolas.TTF,44676,{Convert.ToBase64String(File.ReadAllBytes(@"C:\folderWithFonts\consolas.TTF"))}
        ^fo100,0^A@r,300,300,R:consolas.TTF^fdTESTSTRING^fs^xz");

        var request = (HttpWebRequest)WebRequest.Create("http://api.labelary.com/v1/printers/8dpmm/labels/4.1x5.8/0/");
        request.Method = "POST";
        request.Accept = "application/pdf"; 
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = zpl.Length;

        var requestStream = request.GetRequestStream();
        requestStream.Write(zpl, 0, zpl.Length);
        requestStream.Close();

        try
        {
            var response = (HttpWebResponse)request.GetResponse();
            var responseStream = response.GetResponseStream();
            var fileStream = File.Create(@"C:\folderWithResult\label.pdf"); 
            responseStream.CopyTo(fileStream);
            responseStream.Close();
            fileStream.Close();
        }
        catch (WebException e)
        {
            Console.WriteLine("Error: {0}", e.Status);
        }

I get the following result. Label in pdf was created without Consolas font. So, what am I doing wrong?

Questioner
V. Y.
Viewed
11
V. Y. 2020-10-13 18:23

Problem was fixed after replacing Base64 encoding to the Hex encoding. Replaced

Convert.ToBase64String(File.ReadAllBytes(@"C:\folderWithFonts\consolas.TTF"))

To BitConverter.ToString(File.ReadAllBytes(@"C:\folderWithFonts\consolas.ttf")).Replace("-", "")