This is a migrated thread and some comments may be shown as answers.

Adding the contents of a RadDocument to a table cell when exporting

7 Answers 175 Views
RichTextBox
This is a migrated thread and some comments may be shown as answers.
Martin
Top achievements
Rank 1
Martin asked on 03 Jun 2014, 09:20 PM
I can't figure out how to add the contents of a RadDocument (with styling) to a table cell when exporting to PDF. Any advice on how I should go about solving this?

        private void RadButton_Click(object sender, RoutedEventArgs e)
        {
            var span = new Span();
            span.Text = "Span1";
            var paragraph = new Paragraph();
            paragraph.Inlines.Add(span);
            var tableCell1 = new TableCell();
            tableCell1.Blocks.Add(paragraph);
            
            var tableCell2 = new TableCell();
            tableCell2.Blocks.Add(Editor.Document); // THIS WON'T COMPILE, BUT HOW TO FIX?

            var tableRow = new TableRow();
            tableRow.Cells.Add(tableCell1);
            tableRow.Cells.Add(tableCell2);

            var table = new Table();
            table.AddRow(tableRow);

            var section = new Section();
            section.Blocks.Add(table);

            var document = new RadDocument();
            document.Sections.Add(section);

            var saveFileDialog = new SaveFileDialog();
            saveFileDialog.DefaultExt = ".pdf";
            saveFileDialog.Filter = "Portable Document Format (*.pdf) | *.pdf";

            var result = saveFileDialog.ShowDialog();

            if (result == true)
            {
                using (var saveFileStream = saveFileDialog.OpenFile())
                {
                    var provider = new PdfFormatProvider();

                    provider.Export(document, saveFileStream);
                }
            }
        }

7 Answers, 1 is accepted

Sort by
0
Petya
Telerik team
answered on 05 Jun 2014, 03:20 PM
Hello Martin,

You can create a DocumentFragment from the document and insert it in the specific cell. For this purpose you can take advantage of the RadDocumentEditor class. Please check the snippet below.
var span = new Span();
span.Text = "Span1";
var paragraph = new Paragraph();
paragraph.Inlines.Add(span);
var tableCell1 = new TableCell();
tableCell1.Blocks.Add(paragraph);
 
var tableCell2 = new TableCell();
 
var tableRow = new TableRow();
tableRow.Cells.Add(tableCell1);
tableRow.Cells.Add(tableCell2);
 
var table = new Table();
table.AddRow(tableRow);
 
var section = new Section();
section.Blocks.Add(table);
 
var document = new RadDocument();
document.Sections.Add(section);
document.MeasureAndArrangeInDefaultSize();
document.CaretPosition.MoveToStartOfDocumentElement(tableCell2);
 
RadDocumentEditor editor = new RadDocumentEditor(document);
editor.Document.CaretPosition.MoveToStartOfDocumentElement(tableCell2);
editor.InsertFragment(new DocumentFragment(Editor.Document));
 
 
this.radRichTextBox.Document = editor.Document;
var saveFileDialog = new Microsoft.Win32.SaveFileDialog();
saveFileDialog.DefaultExt = ".pdf";
saveFileDialog.Filter = "Portable Document Format (*.pdf) | *.pdf";
 
var result = saveFileDialog.ShowDialog();
 
if (result == true)
{
    using (var saveFileStream = saveFileDialog.OpenFile())
    {
        var provider = new PdfFormatProvider();
 
        provider.Export(editor.Document, saveFileStream);
    }
}

I hope this helps.

Regards,
Petya
Telerik
 
Check out Telerik Analytics, the service which allows developers to discover app usage patterns, analyze user data, log exceptions, solve problems and profile application performance at run time. Watch the videos and start improving your app based on facts, not hunches.
 
0
Martin
Top achievements
Rank 1
answered on 10 Jun 2014, 08:19 PM
I appreciate your answer, but is it possible without updating the editor before exporting? 

I'd like for it to work without the following line, but removing it results in tableCell2 being empty.

this.radRichTextBox.Document = editor.Document; // IS IT POSSIBLE WITHOUT THIS LINE?
0
Petya
Telerik team
answered on 13 Jun 2014, 03:03 PM
Hello Martin,

Thanks for the follow-up.

You can specify the layout mode of the document you created and everything should work without the mentioned line.
var document = new RadDocument();
document.Sections.Add(section);
 
document.LayoutMode = DocumentLayoutMode.Paged;
document.MeasureAndArrangeInDefaultSize();
document.CaretPosition.MoveToStartOfDocumentElement(tableCell2);

Regards,
Petya
Telerik
 
Check out Telerik Analytics, the service which allows developers to discover app usage patterns, analyze user data, log exceptions, solve problems and profile application performance at run time. Watch the videos and start improving your app based on facts, not hunches.
 
0
Martin
Top achievements
Rank 1
answered on 15 Jun 2014, 10:19 PM
Thanks for the answer, but I've now run into another problem. I'm using the code in a web service that returns the generated PDF and I'm now getting the following error: The calling thread must be STA, because many UI components require this. Please tell me that this is solvable too? :-)


Stack trace:
System.InvalidOperationException was unhandled by user code
  HResult=-2146233079
  Message=The calling thread must be STA, because many UI components require this.
  Source=PresentationCore
  StackTrace:
       at System.Windows.Input.InputManager..ctor()
       at System.Windows.Input.InputManager.GetCurrentInputManagerImpl()
       at System.Windows.Input.KeyboardNavigation..ctor()
       at System.Windows.FrameworkElement.FrameworkServices..ctor()
       at System.Windows.FrameworkElement.EnsureFrameworkServices()
       at System.Windows.FrameworkElement..ctor()
       at System.Windows.Shapes.Line..ctor()
       at Telerik.Windows.Documents.UI.TextDecorations.DecorationProviders.LineDecoration.CreateDecorationUI(RectangleF currentRectangle, Color color)
       at Telerik.Windows.Documents.FormatProviders.Pdf.PdfUnderlineDecorator.FlushSpans(PdfContentsWriter writer)
       at Telerik.Windows.Documents.FormatProviders.Pdf.PdfUnderlineDecorator.AddSpanBox(PdfContentsWriter writer, SpanLayoutBox span)
       at Telerik.Windows.Documents.FormatProviders.Pdf.PdfDocumentExporter.ExportSectionLayoutBox(SectionLayoutBox sectionBox, PdfContentsWriter writer)
       at Telerik.Windows.Documents.FormatProviders.Pdf.PdfDocumentExporter.ExportPage(SectionLayoutBox sectionBox, PdfContentsWriter writer)
       at Telerik.Windows.Documents.FormatProviders.Pdf.PdfDocumentExporter.<>c__DisplayClass1.<Export>b__0(PdfContentsWriter contentsWriter)
       at Telerik.Windows.Documents.FormatProviders.Pdf.RadPdf.PdfContents.WriteContents(PdfWriter writer)
       at Telerik.Windows.Documents.FormatProviders.Pdf.RadPdf.PdfStream.WriteToCore(PdfWriter writer)
       at Telerik.Windows.Documents.FormatProviders.Pdf.RadPdf.PdfObject.WriteTo(PdfWriter writer)
       at Telerik.Windows.Documents.FormatProviders.Pdf.RadPdf.PdfWriter.WritePdfObject(PdfObject obj)
       at Telerik.Windows.Documents.FormatProviders.Pdf.PdfDocumentExporter.Export()
       at Telerik.Windows.Documents.FormatProviders.Pdf.PdfFormatProvider.Export(RadDocument document, Stream output)
       <removed this line for privacy concerns>
       at System.Web.Http.Tracing.Tracers.BufferedMediaTypeFormatterTracer.<>c__DisplayClass7.<WriteToStream>b__6()
       at System.Web.Http.Tracing.ITraceWriterExtensions.TraceBeginEnd(ITraceWriter traceWriter, HttpRequestMessage request, String category, TraceLevel level, String operatorName, String operationName, Action`1 beginTrace, Action execute, Action`1 endTrace, Action`1 errorTrace)
  InnerException: 





0
Petya
Telerik team
answered on 17 Jun 2014, 02:00 PM
Hello Martin,

If you specify the apartment state of the thread to be STA you should no longer observe this exception.
var thread = new Thread(() =>
{
    var span = new Span();
    span.Text = "Span1";
 
    //...
 
    using (var saveFileStream = saveFileDialog.OpenFile())
    {
        var provider = new PdfFormatProvider();
 
        provider.Export(editor.Document, saveFileStream);
    }
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();

Please note that in this case if the Editor RadRichTextBox from the content of which you are creating a fragment contains images, they will not be visible in the generated PDF output. In order to ensure images are visible you need to freeze their image sources prior the export (on the UI thread).
foreach (var image in this.Editor.Document.EnumerateChildrenOfType<ImageInline>())
{
    image.ImageSource.Freeze();
}

I hope this is helpful.

Regards,
Petya
Telerik
 
Check out Telerik Analytics, the service which allows developers to discover app usage patterns, analyze user data, log exceptions, solve problems and profile application performance at run time. Watch the videos and start improving your app based on facts, not hunches.
 
0
Martin
Top achievements
Rank 1
answered on 18 Jun 2014, 12:02 PM
It works. Brilliant :-)

Almost there now. I also want to support exporting to docx, but changing the provider to DocxFormatProvider result in the following error. How to fix?

System.NotSupportedException was unhandled
  HResult=-2146233067
  Message=Stream does not support seeking.
  Source=mscorlib
  StackTrace:
       at System.IO.BufferedStream.get_Position()
       at Telerik.Windows.Zip.ZipArchiveEntry.WriteLocalFileHeader()
       at Telerik.Windows.Zip.ZipArchiveEntry.OpenForWriting()
       at Telerik.Windows.Zip.ZipArchiveEntry.Open()
       at Telerik.Windows.Zip.ZipPackage.AddStream(Stream stream, String fileNameInZip, ZipCompression method, DateTime dateTime, CompressionType compressionType)
       at Telerik.Windows.Zip.ZipPackage.AddStream(Stream stream, String fileNameInZip, ZipCompression method, DateTime dateTime)
       at Telerik.Windows.Documents.FormatProviders.OpenXml.Docx.Export.DocxExporter.AddPartToPackage(Stream partStream, String partPath)
       at Telerik.Windows.Documents.FormatProviders.OpenXml.Docx.Export.ParagraphExporter.ExportImageFile(IImageDocumentElement imageInline, String imageID)
       at Telerik.Windows.Documents.FormatProviders.OpenXml.Docx.Export.ParagraphExporter.ExportImageInline(ImageInline imageInline)
       at Telerik.Windows.Documents.FormatProviders.OpenXml.Docx.Export.ParagraphExporter.ExportInline(Paragraph paragraph, Inline inline)
       at Telerik.Windows.Documents.FormatProviders.OpenXml.Docx.Export.ParagraphExporter.Export(Paragraph paragraph)
       at Telerik.Windows.Documents.FormatProviders.OpenXml.Docx.Export.MainDocumentExporter.ExportParagraph(Paragraph paragraph)
       at Telerik.Windows.Documents.FormatProviders.OpenXml.Docx.Export.MainDocumentExporter.ExportBlock(Block block)
       at Telerik.Windows.Documents.FormatProviders.OpenXml.Docx.Export.TableExporter.ExportTableCell(Table table, TableCellData cellData, MainDocumentExporter exporter)
       at Telerik.Windows.Documents.FormatProviders.OpenXml.Docx.Export.TableExporter.Export(MainDocumentExporter exporter, Table table)
       at Telerik.Windows.Documents.FormatProviders.OpenXml.Docx.Export.MainDocumentExporter.ExportTable(Table table)
       at Telerik.Windows.Documents.FormatProviders.OpenXml.Docx.Export.MainDocumentExporter.ExportBlock(Block block)
       at Telerik.Windows.Documents.FormatProviders.OpenXml.Docx.Export.MainDocumentExporter.Export()
       at Telerik.Windows.Documents.FormatProviders.OpenXml.Docx.Export.DocxExporter.AddXmlContentToPackage(DocxPartExporterBase exporter)
       at Telerik.Windows.Documents.FormatProviders.OpenXml.Docx.Export.DocxExporter.AddXmlContentWithRelationsToPackage(DocxPartExporterBase exporter)
       at Telerik.Windows.Documents.FormatProviders.OpenXml.Docx.Export.DocxExporter.Export()
       at Telerik.Windows.Documents.FormatProviders.OpenXml.Docx.DocxFormatProvider.Export(RadDocument document, Stream output)
       ...
       ...
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:


0
Petya
Telerik team
answered on 23 Jun 2014, 11:26 AM
Hello Martin,

I'm afraid it is hard to say what might be causing this based only on the stack trace. Would it be possible to open a support ticket and send us a sample project showing the error?

We are looking forward to hearing from you.

Regards,
Petya
Telerik
 
Check out Telerik Analytics, the service which allows developers to discover app usage patterns, analyze user data, log exceptions, solve problems and profile application performance at run time. Watch the videos and start improving your app based on facts, not hunches.
 
Tags
RichTextBox
Asked by
Martin
Top achievements
Rank 1
Answers by
Petya
Telerik team
Martin
Top achievements
Rank 1
Share this question
or