Telerik Forums
Telerik Document Processing Forum
3 answers
494 views

I want to import pdf document to a RadFlowWordDocument in the current Run from code.

Is it possible? I have imported pdf using RadEditor.

 

Maria
Telerik team
 answered on 05 Jan 2023
1 answer
288 views

Basically i am trivarsing whole word document template and updating the text of merge field run.
But after updating the text i want to delete the merge field. How to do that?

var currentDocument = document.EnumerateChildrenOfType<DocumentElementBase>().ToList();
                    int indexElement = 0;
                    foreach (var currentElement in currentDocument)
                    { 

if (currentElement.GetType() == typeof(Run))
                        {
                            currentRun = (Run)currentElement;

 if (currentRun.Text.StartsWith("«") && currentRun.Text.Length > 2)
                            {

string runText= currentRun.Text.Substring(1, currentRun.Text.Length - 2);
if(runText == "name")
currentRun.Text = "faraz";

}

Now after updating the text i want to delete the merge field and maintain the run text. How to do that?

Yoan
Telerik team
 answered on 29 Dec 2022
1 answer
138 views

I'm using RadFlowDocument editor to insert a document in a specific position after a text from run.

So flow is read a document runs and when a text is reach insert another RawFlowDocument in it.

But the problem is always adding it in the end.

I want to insert it at specific position. 

There are total 3 documents that needs to be added at specific position.
The run text shows i am at the right position but the generated document always shows new document in the end.

else if (currentRun.Text.EndsWith("Template»"))
                                {

                                    string ebrTemplateName = currentRun.Text.Substring(7, currentRun.Text.Length - 8);
                                    var currentT = ModifyTemplate(ebrTemplateName, jsonToken + "[" + i + "].");
                                    if (currentT != null)
                                    {


                                       // documents.Enqueue(new DocumentsStack { document = currentT, run = currentRun });
                                        currentRun.GetEditorBefore().InsertDocument(currentT);
                                         //editor.InsertDocument(currentT);
                                        
                                    }

                                }
Maria
Telerik team
 answered on 23 Dec 2022
4 answers
218 views

I'm using RadFlowDocument to edit a document (docx), this file is a combination of different docx file.

I have to add Table of content in this file. I saw this code but it is using RadDocument instead of RadFlowDocument class

RadDocument document = new RadDocument();
RadDocumentEditor editor = new RadDocumentEditor(new RadDocument());
editor.InsertField(new TableOfContentsField(), FieldDisplayMode.Result);

How can I add ToC using RadFlowDocument ?

Thanks

Muhammad
Top achievements
Rank 1
Iron
 answered on 22 Dec 2022
1 answer
933 views

I am trying to generate a PDF document but don't know how to control the Page size. As the printout is most likely A4, I would like to print it horizontally in order to fit my table in. The following is my code snippet. The first few rows of the table are the header.

        // ----------------------------------------------
        // Print Request Test Schedule Allocation
        // -----------------------------------------------
        private void cmdPrint_Click(object sender, EventArgs e)
        {
            FixedContentEditor editor;
            RadFixedDocument document;
            RadFixedPage page;

            document = new RadFixedDocument();
            page = document.Pages.AddPage();
            editor = new FixedContentEditor(page, new SimplePosition());           

            Table table = new Table();
            table.BorderCollapse = BorderCollapse.Separate;
            table.LayoutType = TableLayoutType.AutoFit;
            table.Margin = new System.Windows.Thickness(50);

            table = SetTableHeader(table);

            editor.DrawTable(table)

            TableRow tableRow;
            foreach (KeyValuePair<string, TDFCollection> tDFObject in T.FileList)
            {
                Block block = new Block();
                string name = tDFObject.Value.TDFName;
                string desc = tDFObject.Value.TDFDescription;
                string requester = tDFObject.Value.Requester;
                string duration = tDFObject.Value.Duration.ToString();

                tableRow = table.Rows.AddTableRow();
                tableRow.Cells.AddTableCell().PreferredWidth = 20;
                block = tableRow.Cells.AddTableCell().Blocks.AddBlock();
                block.TextProperties.FontSize = 12;
                block.InsertText(name);
                tableRow.Cells.AddTableCell().PreferredWidth = 30;
                block = tableRow.Cells.AddTableCell().Blocks.AddBlock();
                block.TextProperties.FontSize = 12;
                block.InsertText(desc);
                tableRow.Cells.AddTableCell().PreferredWidth = 35;
                block = tableRow.Cells.AddTableCell().Blocks.AddBlock();
                block.TextProperties.FontSize = 12;
                block.InsertText(requester);
                tableRow.Cells.AddTableCell().PreferredWidth = 5;
                block = tableRow.Cells.AddTableCell().Blocks.AddBlock();
                block.HorizontalAlignment = Telerik.Windows.Documents.Fixed.Model.Editing.Flow.HorizontalAlignment.Center;
                block.TextProperties.FontSize = 12;
                block.InsertText(duration);                
            }
            editor.DrawTable(table);

            int index = 0;
            string agendaFile = null;
            while (true)
            {
                index++;
                agendaFile = T.TEST_Scheduling + "Request Allocation" + " (" + index.ToString() + ").pdf";
                if (!File.Exists(agendaFile)) break;
            }

            PdfFormatProvider provider = new PdfFormatProvider();
            try
            {
                using (Stream output = File.OpenWrite(agendaFile))
                {
                    provider.Export(document, output);
                }
            }
            catch (Exception ex)
            {
                T.WriteLine("PDF Stream Write Exception : " + ex.Message);
                MessageBox.Show(ex.Message, "PDF Output Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            MessageBox.Show("Test Schedule Allocation Requests PDF is created", "Print Test Allocation Requests", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        // ---------------
        //  Set PDF Header
        // ---------------
        private Table SetTableHeader(Table table)
        {
            TableRow tableRow;
            tableRow = table.Rows.AddTableRow();
            tableRow.Cells.AddTableCell().PreferredWidth = 30;
            Block block = tableRow.Cells.AddTableCell().Blocks.AddBlock();
            block.TextProperties.FontSize= 14;
            block.GraphicProperties.FillColor = new RgbColor(0, 0, 139);
            block.InsertText("TEST SCHEDULING REQUESTS");         

            tableRow = table.Rows.AddTableRow();
            block = tableRow.Cells.AddTableCell().Blocks.AddBlock();
            block.TextProperties.FontSize = 12;
            block.InsertText(" ");

            tableRow = table.Rows.AddTableRow();
            tableRow.Cells.AddTableCell().PreferredWidth = 30;
            block.TextProperties.FontSize = 12;
            block = tableRow.Cells.AddTableCell().Blocks.AddBlock();           
            block.GraphicProperties.FillColor = new RgbColor(0, 0, 139);
            block.TextProperties.UnderlineColor = new RgbColor(0, 0, 139);
            block.InsertText("Test Definition");
            block.InsertLineBreak();

            tableRow.Cells.AddTableCell().PreferredWidth = 30;
            block = tableRow.Cells.AddTableCell().Blocks.AddBlock();
            block.TextProperties.FontSize = 12;
            block.GraphicProperties.FillColor = new RgbColor(0, 0, 139);
            block.TextProperties.UnderlineColor = new RgbColor(0, 0, 139);
            block.InsertText("Description");

            tableRow.Cells.AddTableCell().PreferredWidth = 35;
            block = tableRow.Cells.AddTableCell().Blocks.AddBlock();
            block.TextProperties.FontSize = 12;
            block.GraphicProperties.FillColor = new RgbColor(0, 0, 139);
            block.TextProperties.UnderlineColor = new RgbColor(0, 0, 139);
            block.InsertText("Requester");

            tableRow.Cells.AddTableCell().PreferredWidth = 5;
            block = tableRow.Cells.AddTableCell().Blocks.AddBlock();
            block.TextProperties.FontSize = 12;
            block.GraphicProperties.FillColor = new RgbColor(0, 0, 139);
            block.TextProperties.UnderlineColor = new RgbColor(0, 0, 139);
            block.InsertText("Duration");

            block = tableRow.Cells.AddTableCell().Blocks.AddBlock();
            block.TextProperties.FontSize = 12;
            block.InsertText("    ");

            return table;
        }   
    }

                                      
Yoan
Telerik team
 answered on 14 Dec 2022
1 answer
533 views

Hi, i'm trying to use document processing to convert HTML template to PDF, but fonts are missing from resulting file, maybe even from the imported html.

How can I find out if the fonts are already missing after importing HTML?

What is the best way to convert HTML to PDF keeping images, fonts, etc. using document processing?

This is one of my attempts to get it to work.

static void Main(string[] args)
        {
            string templateFileName = @"html template.htm";
            string pdfPath = @"test html template to pdf.pdf";
            FileStream templateAsStream = new FileStream(templateFileName, FileMode.Open, FileAccess.Read);

            ///////////
            //telerik
            ///////////

            

            try
            {               
                // Register the font 
                byte[] fontDataR = File.ReadAllBytes("Raleway-VariableFont_wght.ttf");
                System.Windows.Media.FontFamily fontFamilyR = new System.Windows.Media.FontFamily("Releway");
                byte[] fontDataRL = File.ReadAllBytes("Raleway-Light.ttf");
                System.Windows.Media.FontFamily fontFamilyRL = new System.Windows.Media.FontFamily("Releway Light");

                //Telerik.Windows.Documents.Fixed.Model.Fonts.
                FontsRepository.RegisterFont(fontFamilyR, System.Windows.FontStyles.Normal, System.Windows.FontWeights.Normal, fontDataR);
                FontsRepository.RegisterFont(fontFamilyRL, System.Windows.FontStyles.Normal, System.Windows.FontWeights.Normal, fontDataRL);

                byte[] fontDataRb = File.ReadAllBytes("Raleway-Bold.ttf");
                System.Windows.Media.FontFamily fontFamilyRb = new System.Windows.Media.FontFamily("Releway");
                //Telerik.Windows.Documents.Fixed.Model.Fonts.
                FontsRepository.RegisterFont(fontFamilyR, System.Windows.FontStyles.Normal, System.Windows.FontWeights.Bold, fontDataRb);


                //import AFTER setting fonts
                //Telerik.Windows.Documents.Flow.FormatProviders.Html.
                HtmlFormatProvider htmlProvider = new HtmlFormatProvider();
                HtmlImportSettings importSettings = new HtmlImportSettings();
                HtmlExportSettings exportSettings = new HtmlExportSettings();
                var document = htmlProvider.Import(templateAsStream);                

                PdfFormatProvider pdfProvider = new PdfFormatProvider();

                //Telerik.Windows.Documents.Extensibility.FontsProviderBase fontsProvider = new FontsProvider();
                //Telerik.Windows.Documents.Extensibility.FixedExtensibilityManager.FontsProvider = fontsProvider;

                PdfExportSettings pdfExportSettings = new PdfExportSettings();
                pdfExportSettings.ShouldEmbedFonts = true;

                pdfProvider.ExportSettings = pdfExportSettings;


                FileStream stream = File.Create("fixed pdf.pdf");
                var radFixedDocument = (new Telerik.Windows.Documents.Flow.FormatProviders.Pdf.PdfFormatProvider()).ExportToFixedDocument(document);
                var fixedFormatProvider = new Telerik.Windows.Documents.Fixed.FormatProviders.Pdf.PdfFormatProvider();
                fixedFormatProvider.Export(radFixedDocument, stream);
                stream.Close();

                //var resultBytes = pdfProvider.Export(document);
                //File.WriteAllBytes(pdfPath, resultBytes);

            }
            catch(Exception e)
            {
                throw e;
            }

I have also attached html file that is result of importing html and then export html

 

also I get this in pdf reader both if I use embed fonts option or not

 

https://www.telerik.com/forums/radflowdocument-to-pdf---arialnarrow-font-issues

Maria
Telerik team
 answered on 12 Dec 2022
1 answer
156 views
Hello,

I have two, semi-related questions.

Question 1: Is it possible append pages using PDFStreamWriter to an existing document without fully overwriting it and wiping out the Document level properties?

I need to create a PDF report that is a combination of code generated pages and an appendix of externally sourced PDFs (cut sheets, specification documents, etc.). Since I don't need to modify the appendix PDFs, I'd like to create the code portion using the RadFixedDocument and then attach the appendix PDFs using the more memory efficient PDFStreamWriter. Unfortunately, I need to retain bookmarks, interactive form fields and other document level data from the code generated portion, so I can't use the Page-by-Page Stream merge shown in your examples.

I would much prefer to use the PDFStreamWriter merge method since, again, I do not modify the appendix PDFs and, since the PDFs can be quite large, the memory footprint with RadFixedDocument is very high.

Question 2: Is there a way to direct which font is used for unrecognized Font types during import? Alternatively, is there a setting I can apply so Merged/Imported PDF content will not be modified?

Assuming I need to use RadFixedDocument to maintain the bookmarks, when I import some appendix PDFs any non-embedded fonts that aren't recognized are defaulted to Helvetica. This results in a bad presentation of the final merged export. This occurs even when I manually register the font in the FontsRepository before importing.

Attached are example images and a Zip containing the PDF and Font ttf.

I am using the Telerik.Windows.Documents.Fixed API for .NET Framework.

Thank you,
Aidan D.
Dimitar
Telerik team
 answered on 09 Dec 2022
1 answer
267 views

Hi 

I am working on code to read DOCX from user, then I will replace text in DOCX by our data. 

Anyway, I want to validate all font that is used by uploaded document. Can you provide me code snippet?

I have debugged Run, StyleRepository, Paragrah but no luck. it just display default Verdana.

Yoan
Telerik team
 answered on 06 Dec 2022
0 answers
229 views

Hello,

This post is not a question.  I simply wanted to share my partial solution for those who may need it.

Below is a manual method for creating a Block with justified text in the PDFProcessing API.  This makes use of the Block object's Measure method and the WordSpacing property to adjust each line until the indicated width is filled. 

PLEASE NOTE:

  • While I tried to account for it, I have not tested this code for compatibility with multiple paragraphs or blank lines. 
  • It is intended for small portions of text and will not likely scale well with a full document.

Best Regards,

Aidan D.

TAGS FOR GOOGLE: Justify, Alignment

using System; using System.Collections.Generic; using Telerik.Windows.Documents.Fixed.Model.Editing; using Telerik.Windows.Documents.Fixed.Model.Fonts; classTextJustify { public static void InsertJustifiedBlock(FixedContentEditor PageEditor, string Text, int TextBoxWidth) { Block justifiedBlock = CreateJustifiedBlock(Text, TextBoxWidth, PageEditor.TextProperties.Font, PageEditor.TextProperties.FontSize); PageEditor.DrawBlock(justifiedBlock); } public static Block CreateJustifiedBlock(string Text, int TextBoxWidth, FontBase Font, double FontSize) { Block justifiedBlock = new Block(); double currentSpacing = 0; double spacingStep = 1; string currentLine; if (Text.Length > 0) { { var withBlock = justifiedBlock.TextProperties; // Default word spacing. Must be initialized to 0 before use. This defaults to Nothing/Null// and will not function correctly if not initialized. withBlock.WordSpacing = 0; withBlock.Font = Font; withBlock.FontSize = FontSize; } // We need a seperate block to use as a measuring tool using the same text properties as the justified block. Block measuringBlock = new Block(justifiedBlock); // Make sure the WordSpacing property is initialized to zero. // Break the text string into lines, adding as many full words as we can to each line.// This does not support hyphenation. List<string> lines = breakIntoLines(Text, TextBoxWidth, ref measuringBlock); for (int i = 0; i <= lines.Count - 1; i++) { currentLine = lines[i]; // For all except the last line, space out the words to fill the allowed space.if (i < (lines.Count - 1)) { do { // Set the word spacing before inserting the text. measuringBlock.TextProperties.WordSpacing = currentSpacing; // We need to reinsert the text each time the spacing changes since the spacing is only applied on insert measuringBlock.Clear(); measuringBlock.InsertText(currentLine); measuringBlock.Measure(); if (measuringBlock.DesiredSize.Width > TextBoxWidth && spacingStep != 0.01) { // Step back by one then narrow in at finer increments currentSpacing -= spacingStep; spacingStep /= 10; currentSpacing += spacingStep; continue; } currentSpacing += spacingStep; } while (measuringBlock.DesiredSize.Width > TextBoxWidth && spacingStep == 0.01); // Reduce by one step to bring it back into allowed width currentSpacing -= spacingStep; } // Add the line of text with the appropriate spacing.using (justifiedBlock.SaveTextProperties()) { justifiedBlock.TextProperties.WordSpacing = currentSpacing; justifiedBlock.InsertText(currentLine); justifiedBlock.InsertLineBreak(); } // Reset for next line currentSpacing = 0; spacingStep = 1; } } return justifiedBlock; } private static List<string> breakIntoLines(string Text, int maxLineWidth, ref Block measuringBlock) { List<string> sResults = new List<string>(); string[] lines = Text.Split(newstring[] { "\n", "\r\n" }, StringSplitOptions.None); foreach (string line in lines) { string[] words = line.Split(newstring[] { " " }, StringSplitOptions.RemoveEmptyEntries); sResults.Add(""); // Initialize the line. This may remain empty if the line is blank.for (int i = 0; i <= words.Length - 1; i++) { if (sResults[sResults.Count - 1].Length == 0) sResults[sResults.Count - 1] = words[i]; else { string testLine = string.Concat(sResults[sResults.Count - 1], " ", words[i]); measuringBlock.InsertText(testLine); measuringBlock.Measure(); if (measuringBlock.DesiredSize.Width <= maxLineWidth) // Replace with new, longer line sResults[sResults.Count - 1] = testLine; else// Start new line sResults.Add(words[i]); // Remove text from measuring block to reset for next word measuringBlock.Clear(); } } } return sResults; } }


Aidan
Top achievements
Rank 1
 updated question on 05 Dec 2022
1 answer
135 views

Hi,
there seems to be a bug in the PdfFormatProvider Import code.

When using swedish culture, the read PDF data has incorrect position matrices, causing all elements to disappear.

Example ("en"):

{
    "Matrix": {
        "IsIdentity": false,
        "Determinant": 1.7777777777777777,
        "M11": 1.3333333333333333,
        "M12": 0,
        "M21": 0,
        "M22": 1.3333333333333333,
        "OffsetX": 0,
        "OffsetY": 0
    }
}

Example ("sv"):

{
    "Matrix": {
        "IsIdentity": false,
        "Determinant": 0,
        "M11": 1.3333333333333333,
        "M12": 0,
        "M21": 0,
        "M22": 0,
        "OffsetX": 0,
        "OffsetY": 0
    }
}

 

Once found, it's easy for me to work around this big.
But it looks like it should be easy to fix!

Thanks,
Anton

Martin
Telerik team
 answered on 02 Dec 2022
Narrow your results
Selected tags
Tags
+? more
Top users last month
Jay
Top achievements
Rank 3
Iron
Iron
Iron
yw
Top achievements
Rank 2
Iron
Iron
Stefan
Top achievements
Rank 2
Iron
Iron
Iron
Kao Hung
Top achievements
Rank 1
Iron
Bohdan
Top achievements
Rank 2
Iron
Iron
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Jay
Top achievements
Rank 3
Iron
Iron
Iron
yw
Top achievements
Rank 2
Iron
Iron
Stefan
Top achievements
Rank 2
Iron
Iron
Iron
Kao Hung
Top achievements
Rank 1
Iron
Bohdan
Top achievements
Rank 2
Iron
Iron
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?