Spire.Doc is a professional Word .NET library specifically designed for developers to create, read, write, convert and print Word document files. Get free and professional technical support for Spire.Doc for .NET, Java, Android, C++, Python.

Tue Sep 03, 2024 12:38 pm

Hello,

After converting docx with embedded fonts in to pdf fonts are changed.

Code: Select all
public static void CreatePdfFromWordTemplate(string wordTemplateFilePath, string outputFilePath)
{
    var person = new Person()
    {
        FirstName = "Иван",
        MiddleName = "Терзиев",
        FamilyName = "Иванов",
        CountryOfBirth = "България",
        DateOfBirth = DateTime.Now.AddYears(-30),
        PersonalIdentifierType = PersonalIdentifierTypes.LNCH,
        Email = "test@abv.bg",
        PhoneNumber = "1234567890",
        PersonalIdentifier = "1010101010",
        PlaceOfBirth = "София"
    };

    using (var wordMs = new MemoryStream())
    {
        using (Document document = new Document())
        {
            document.LoadFromFile(wordTemplateFilePath);

            var tblApplicant = FindTableByTitle("Applicant", document);

            if (tblApplicant == null)
                throw new NotSupportedException("Invalid word Template.");

            var data = new List<(string label, string value)>()
            {
                ("Име, презиме, фамилия", person.FullName),
                ("ЕГН/ЛНЧ", person.PersonalIdentifier),
                ("Място на раждане", person.FullPlaceOfBirth),
                ("Адрес на електронна поща", person.Email),
                ("Телефон", person.PhoneNumber),
            };

            var tbl = tblApplicant.Rows[1].Cells[0].Tables[0];

            FillCustomTable(1, tbl, data, (r, d) =>
            {
                SetFormFieldText(r.Cells[0].FormFields[0], d.label);
                SetFormFieldText(r.Cells[1].FormFields[0], d.value);
            });

            document.SaveToStream(wordMs, FileFormat.Docx);
        }

        //Fix SPire.Doc bug SPIREDOC-10733 about file links problems.
        using (var doc = new Document())
        {
            wordMs.Position = 0;
            doc.LoadFromStream(wordMs, FileFormat.Docx);

            ToPdfParameterList pdfParams = new ToPdfParameterList();
            pdfParams.IsEmbeddedAllFonts = true; //Try to use word fonts

            doc.SaveToFile(outputFilePath, pdfParams);

            wordMs.Dispose();
        }

        //Embed source in pdf.
        using (var pdfDoc = new Spire.Pdf.PdfDocument(outputFilePath))
        {
            var sourceJson = JsonSerializer.SerializeToUtf8Bytes(person, DefaultJsonSerializationOptions.GetDefaultSerializerOptions());
            pdfDoc.Attachments.Add(new PdfAttachment("source.json", sourceJson));

            pdfDoc.SaveToFile(outputFilePath);
        }
    }
}

Georgi17
 
Posts: 8
Joined: Wed Jul 31, 2024 7:47 am

Tue Sep 03, 2024 12:40 pm

Code: Select all
public class PdfTests
{
    public static void CreatePdfFromWordTemplate(string wordTemplateFilePath, string outputFilePath)
    {
        var person = new Person()
        {
            FirstName = "Иван",
            MiddleName = "Терзиев",
            FamilyName = "Иванов",
            CountryOfBirth = "България",
            DateOfBirth = DateTime.Now.AddYears(-30),
            PersonalIdentifierType = PersonalIdentifierTypes.LNCH,
            Email = "test@abv.bg",
            PhoneNumber = "1234567890",
            PersonalIdentifier = "1010101010",
            PlaceOfBirth = "София"
        };

        using (var wordMs = new MemoryStream())
        {
            using (Document document = new Document())
            {
                document.LoadFromFile(wordTemplateFilePath);

                var tblApplicant = FindTableByTitle("Applicant", document);

                if (tblApplicant == null)
                    throw new NotSupportedException("Invalid word Template.");

                var data = new List<(string label, string value)>()
                {
                    ("Име, презиме, фамилия", person.FullName),
                    ("ЕГН/ЛНЧ", person.PersonalIdentifier),
                    ("Място на раждане", person.FullPlaceOfBirth),
                    ("Адрес на електронна поща", person.Email),
                    ("Телефон", person.PhoneNumber),
                };

                var tbl = tblApplicant.Rows[1].Cells[0].Tables[0];

                FillCustomTable(1, tbl, data, (r, d) =>
                {
                    SetFormFieldText(r.Cells[0].FormFields[0], d.label);
                    SetFormFieldText(r.Cells[1].FormFields[0], d.value);
                });

                document.SaveToStream(wordMs, FileFormat.Docx);
            }

            //Fix SPire.Doc bug SPIREDOC-10733 about file links problems.
            using (var doc = new Document())
            {
                wordMs.Position = 0;
                doc.LoadFromStream(wordMs, FileFormat.Docx);

                ToPdfParameterList pdfParams = new ToPdfParameterList();
                pdfParams.IsEmbeddedAllFonts = true; //Try to use word fonts

                doc.SaveToFile(outputFilePath, pdfParams);

                wordMs.Dispose();
            }

            //Embed source in pdf.
            using (var pdfDoc = new Spire.Pdf.PdfDocument(outputFilePath))
            {
                var sourceJson = JsonSerializer.SerializeToUtf8Bytes(person, DefaultJsonSerializationOptions.GetDefaultSerializerOptions());
                pdfDoc.Attachments.Add(new PdfAttachment("source.json", sourceJson));

                pdfDoc.SaveToFile(outputFilePath);
            }
        }
    }

    #region Helpers

    private static Table FindTableByTitle(string title, Document document)
    {
        Table res = null;

        foreach (Section section in document.Sections)
        {
            foreach (ITable tbl in section.Tables)
            {
                if (tbl is Table t && t.Title == title)
                {
                    res = t;
                    break;
                }
            }
        }

        return res;
    }

    private static Section GetTableSection(Table table)
    {
        foreach (Section s in table.Document.Sections)
        {
            foreach (ITable tbl in s.Tables)
            {
                if (tbl is Table t && t.Title == table.Title)
                    return s;
            }
        }

        return null;
    }

    private static void DeleteTable(Table table)
    {
        var tableSection = GetTableSection(table);

        tableSection.Tables.Remove(table);
    }

    private static void FillCustomTable<T>(int startDataRowNum, ITable table, List<T> data, Action<TableRow, T> rowFiller)
    {
        int startRowNum = startDataRowNum;
        TableRow nextRow = table.Rows[startRowNum].Clone();

        foreach (T rowData in data)
        {
            TableRow currRow;

            if (startRowNum == 1)
            {
                currRow = table.Rows[startRowNum];
                startRowNum++;
            }
            else
            {
                currRow = nextRow;
                table.Rows.Insert(startRowNum++, nextRow);
                nextRow = nextRow.Clone();
            }

            rowFiller(currRow, rowData);
        }
    }

    private static string GetObjectValueAsString(object value, string strFormat = null)
    {
        if (value == null) return "";

        Type ValType = value.GetType();

        if (ValType == typeof(Int16))
        {
            return string.IsNullOrEmpty(strFormat) ? ((Int16)value).ToString("D") : ((Int16)value).ToString(strFormat, CultureInfo.CreateSpecificCulture("bg-BG"));
        }
        else if (ValType == typeof(Int32))
        {
            return string.IsNullOrEmpty(strFormat) ? ((Int32)value).ToString("D") : ((Int32)value).ToString(strFormat, CultureInfo.CreateSpecificCulture("bg-BG"));
        }
        else if (ValType == typeof(Int64))
        {
            return string.IsNullOrEmpty(strFormat) ? ((Int64)value).ToString("D") : ((Int64)value).ToString(strFormat, CultureInfo.CreateSpecificCulture("bg-BG"));
        }
        else if (ValType == typeof(decimal))
        {
            return string.IsNullOrEmpty(strFormat) ? ((decimal)value).ToString("F2") : ((decimal)value).ToString(strFormat, CultureInfo.CreateSpecificCulture("bg-BG"));
        }
        else if (ValType == typeof(DateTime))
        {
            return string.IsNullOrEmpty(strFormat) ? ((DateTime)value).ToString("dd.MM.yyyy г.") : ((DateTime)value).ToString(strFormat, CultureInfo.CreateSpecificCulture("bg-BG"));
        }
        else
            return value.ToString();
    }

    private static void SetFormFieldText(FormField formField, object value)
    {
        if (value == null) return;

        formField.Text = GetObjectValueAsString(value);
    }

    #endregion
}

Georgi17
 
Posts: 8
Joined: Wed Jul 31, 2024 7:47 am

Wed Sep 04, 2024 3:04 am

Hello,

Thanks for your inquiry.I have reviewed the document in your attachment and found that the font in 'WordTemplate. docx' is 'Fira Sans'. I suspect the problem lies in the fact that this font is not installed on your system. If you have already installed this font, please ensure that everyone has access to the installed font. Then you can convert again. If your issue still persists, please provide us with your system information (E.g. Win10, 64 bit) and region setting (E.g. China, Chinese). Thank you in advance.

Sincerely,
Amin
E-iceblue support team
User avatar

Amin.Gan
 
Posts: 164
Joined: Mon Jul 15, 2024 5:40 am

Mon Sep 09, 2024 6:56 am

Hello,

Thank you for replay.
I try to set fonts like this:

Code: Select all
ToPdfParameterList pdfParams = new ToPdfParameterList();
pdfParams.IsEmbeddedAllFonts = true; //Try to use word fonts

pdfParams.PrivateFontPaths = new List<PrivateFontPath>()
{
    new PrivateFontPath("Fira Sans Light", "app\\Fonts\\FiraSans-Light.otf",
    new PrivateFontPath("Fira Sans Medium", "app\\Fonts\\FiraSans-Medium.otf"
};

doc.SaveToStream(pdfStream, pdfParams);


But still code throws same exception "Cannot found font installed on the system.".

Is it mandatory to install in linux container word fonts?
Also is there any specific things for linux distribution red hat 8 for open shift?

Thank you in advance.

Georgi17
 
Posts: 8
Joined: Wed Jul 31, 2024 7:47 am

Mon Sep 09, 2024 7:58 am

This is Exception details:

{
"type": "https://httpstatuses.io/500",
"title": "GL_INTERNAL_SERVER_ERROR_E",
"status": 500,
"detail": "Cannot found font installed on the system.",
"exceptionDetails": [
{
"message": "Cannot found font installed on the system.",
"type": "System.InvalidOperationException",
"raw": "System.InvalidOperationException: Cannot found font installed on the system.\n at spr㷃.蕮(String A_0, FontStyle A_1, String A_2)\n at spr䈧.廼(String A_0, Single A_1, FontStyle A_2, String A_3, FontStyle A_4)\n at spr䈧.廼(String A_0, Single A_1, FontStyle A_2, String A_3)\n at spr䈧.廼(String A_0, Single A_1, FontStyle A_2)\n at sprꝓ.廼(String A_0, Single A_1, FontStyle A_2)\n at sprꝓ.廼(String A_0, Single A_1)\n at spr흍..ctor()\n at sprꩌ..ctor()\n at Spire.Doc.Layout.Fields.FieldOptions..ctor()\n at Spire.Doc.Document.get_FieldOptions()\n at spr䛲.愮(sprꂔ A_0)\n at spr䛲.扇(sprꂔ A_0)\n at spr䛲.欏(spr㽃 A_0)\n at spr䛲.湚(spr㽃 A_0)\n at spr䛲.熥(spr㽃 A_0)\n at spr䛲.怕(spr䁜 A_0)\n at spr䛲.廼(spr䨽 A_0, spr䨽 A_1)\n at spr䛲.廼(DocumentObject A_0, spr䛲 A_1)\n at spr䛲.愮(DocumentObject A_0)\n at Spire.Doc.Document.愮()\n at Spire.Doc.Document.廼(Stream A_0, ToPdfParameterList A_1, FileFormat A_2)\n at Spire.Doc.Document.摹(Stream A_0, ToPdfParameterList A_1)\n at Spire.Doc.Document.SaveToStream(Stream stream, ToPdfParameterList paramList)\n at FC.Pdf.PdfCreator.CreatePdf(Stream docWordTemplate, Byte[] jsonSource, Action`1 wordFiller) in C:\\Projects\\NFK\\src\\dotnet\\FC.Pdf\\PdfCreator.cs:line 40\n at FC.StructuredDocuments.Service.Services.ApplicationFormDocumentService.TransformToPdf(PdfRequest request) in C:\\Projects\\NFK\\src\\dotnet\\FC.StructuredDocuments.Service\\Services\\ApplicationFormDocumentService.cs:line 67\n at FC.StructuredDocuments.Service.Controllers.DocumentsController.TransformToPdfAsync(PdfRequest request) in C:\\Projects\\NFK\\src\\dotnet\\FC.StructuredDocuments.Service\\Controllers\\DocumentsController.cs:line 106\n at lambda_method5(Closure, Object, Object[])\n at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncActionResultExecutor.Execute(ActionContext actionContext, IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)\n at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()\n at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)\n at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()\n--- End of stack trace from previous location ---\n at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)\n at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)\n at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()\n--- End of stack trace from previous location ---\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)\n at Prometheus.HttpMetrics.HttpRequestDurationMiddleware.Invoke(HttpContext context)\n at Prometheus.HttpMetrics.HttpRequestCountMiddleware.Invoke(HttpContext context)\n at Prometheus.HttpMetrics.HttpInProgressMiddleware.Invoke(HttpContext context)\n at Hellang.Middleware.ProblemDetails.ProblemDetailsMiddleware.Invoke(HttpContext context)",
"stackFrames": [
{
"function": "spr㷃.蕮(string A_0, FontStyle A_1, string A_2)"
},
{
"function": "spr䈧.廼(string A_0, float A_1, FontStyle A_2, string A_3, FontStyle A_4)"
},
{
"function": "spr䈧.廼(string A_0, float A_1, FontStyle A_2, string A_3)"
},
{
"function": "spr䈧.廼(string A_0, float A_1, FontStyle A_2)"
},
{
"function": "sprꝓ.廼(string A_0, float A_1, FontStyle A_2)"
},
{
"function": "sprꝓ.廼(string A_0, float A_1)"
},
{
"function": "spr흍..ctor()"
},
{
"function": "sprꩌ..ctor()"
},
{
"function": "Spire.Doc.Layout.Fields.FieldOptions..ctor()"
},
{
"function": "Spire.Doc.Document.get_FieldOptions()"
},
{
"function": "spr䛲.愮(sprꂔ A_0)"
},
{
"function": "spr䛲.扇(sprꂔ A_0)"
},
{
"function": "spr䛲.欏(spr㽃 A_0)"
},
{
"function": "spr䛲.湚(spr㽃 A_0)"
},
{
"function": "spr䛲.熥(spr㽃 A_0)"
},
{
"function": "spr䛲.怕(spr䁜 A_0)"
},
{
"function": "spr䛲.廼(spr䨽 A_0, spr䨽 A_1)"
},
{
"function": "spr䛲.廼(DocumentObject A_0, spr䛲 A_1)"
},
{
"function": "spr䛲.愮(DocumentObject A_0)"
},
{
"function": "Spire.Doc.Document.愮()"
},
{
"function": "Spire.Doc.Document.廼(Stream A_0, ToPdfParameterList A_1, FileFormat A_2)"
},
{
"function": "Spire.Doc.Document.摹(Stream A_0, ToPdfParameterList A_1)"
},
{
"function": "Spire.Doc.Document.SaveToStream(Stream stream, ToPdfParameterList paramList)"
},
{
"filePath": "C:\\Projects\\NFK\\src\\dotnet\\FC.Pdf\\PdfCreator.cs",
"fileName": "C:\\Projects\\NFK\\src\\dotnet\\FC.Pdf\\PdfCreator.cs",
"function": "FC.Pdf.PdfCreator.CreatePdf(Stream docWordTemplate, byte[] jsonSource, Action<Document> wordFiller)",
"line": 40
},
{
"filePath": "C:\\Projects\\NFK\\src\\dotnet\\FC.StructuredDocuments.Service\\Services\\ApplicationFormDocumentService.cs",
"fileName": "C:\\Projects\\NFK\\src\\dotnet\\FC.StructuredDocuments.Service\\Services\\ApplicationFormDocumentService.cs",
"function": "FC.StructuredDocuments.Service.Services.ApplicationFormDocumentService.TransformToPdf(PdfRequest request)",
"line": 67
},
{
"filePath": "C:\\Projects\\NFK\\src\\dotnet\\FC.StructuredDocuments.Service\\Controllers\\DocumentsController.cs",
"fileName": "C:\\Projects\\NFK\\src\\dotnet\\FC.StructuredDocuments.Service\\Controllers\\DocumentsController.cs",
"function": "FC.StructuredDocuments.Service.Controllers.DocumentsController.TransformToPdfAsync(PdfRequest request)",
"line": 106
},
{
"function": "lambda_method5(Closure , object , object[] )"
},
{
"function": "Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor+SyncActionResultExecutor.Execute(ActionContext actionContext, IActionResultTypeMapper mapper, ObjectMethodExecutor executor, object controller, object[] arguments)"
},
{
"function": "Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()"
},
{
"function": "Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)"
},
{
"function": "Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()"
},
{
"function": "Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)"
},
{
"function": "Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)"
},
{
"function": "Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()"
},
{
"function": "Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)"
},
{
"function": "Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)"
},
{
"function": "Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)"
},
{
"function": "Prometheus.HttpMetrics.HttpRequestDurationMiddleware.Invoke(HttpContext context)"
},
{
"function": "Prometheus.HttpMetrics.HttpRequestCountMiddleware.Invoke(HttpContext context)"
},
{
"function": "Prometheus.HttpMetrics.HttpInProgressMiddleware.Invoke(HttpContext context)"
},
{
"function": "Hellang.Middleware.ProblemDetails.ProblemDetailsMiddleware.Invoke(HttpContext context)"
}
]
}
],
"traceId": "00-3798749fcb268fd5d63aa0d0f96823a3-94f63dfbe1d01a1b-00"
}

Georgi17
 
Posts: 8
Joined: Wed Jul 31, 2024 7:47 am

Mon Sep 09, 2024 10:29 am

Above code work on windows 11 without installed fonts

Georgi17
 
Posts: 8
Joined: Wed Jul 31, 2024 7:47 am

Tue Sep 10, 2024 6:28 am

Hello,

Thank you for your feedback. When you run the program in a Linux container, please ensure that the corresponding fonts are installed in your container and that your program has access permissions.
Your Win11 system runs without any errors, it may be because you have the corresponding font on your system, or because the Win11 system itself has many fonts, our product will find some alternative fonts that support this glyph, so that the program will not error. However, the initialization container does not have any fonts, if you do not install any fonts, there will be errors. You can install the attached fonts under /usr/share/fonts for your container and test again.

Sincerely,
Amin
E-iceblue support team
User avatar

Amin.Gan
 
Posts: 164
Joined: Mon Jul 15, 2024 5:40 am

Tue Sep 10, 2024 7:07 am

Thank you!
I resolve problem by installing fonts as you mentioned, also replace nuget Spire.Doc with Spire.DocFor.NetStandart, because of System.Drawing.Common.dll which can be used only on widnows OS and also nuget SkiaSharp.NativeAssets.Linux.NoDependencies, because of strange exception "Unable to load shared library 'libSkiaSharp' or one of its dependencies on Linux" and finally all work. I hope this will save a lot of time for some one else.

Georgi17
 
Posts: 8
Joined: Wed Jul 31, 2024 7:47 am

Wed Sep 11, 2024 2:19 am

Hello,

Thank you for your feedback! We're very pleased to hear that your issue has been resolved. The operations you took were entirely appropriate. Indeed, from .NET 6, System.Drawing.Common.dll is no longer supported on non-Windows systems. Your sharing of this experience will also be helpful to other customers, and we express our sincere gratitude for that.

Sincerely,
Amin
E-iceblue support team
User avatar

Amin.Gan
 
Posts: 164
Joined: Mon Jul 15, 2024 5:40 am

Return to Spire.Doc

cron