PDFsharp & MigraDoc Foundation

PDFsharp - A .NET library for processing PDF & MigraDoc Foundation - Creating documents on the fly
It is currently Thu Mar 28, 2024 12:34 pm

All times are UTC


Forum rules


Please read this before posting on this forum: Forum Rules



Post new topic Reply to topic  [ 10 posts ] 
Author Message
PostPosted: Sun Aug 08, 2010 6:22 am 
Offline

Joined: Sun Aug 08, 2010 5:48 am
Posts: 1
Hi all, I am trying to use MigraDoc Foundation version 1.31, GDI+ build, to render image from system memory stream using MigraDoc.Rendering.Forms.DocumentPreview and I received 'stream.ReadTimeout' threw an exception of type 'System.InvalidOperationException' at stream argument in my code below.

I tried to add image stream into MigraDoc.DocumentObjectModel.dll but without success. Any help in this regard would be very much appreciated as I am still trying to learn programming in c# :? . Thanks in advance.

Kind Regards,
Rick

Code:

//Program.cs
//==========

    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Viewer());

        }
    }


//Viewer.cs
//==========
   using MigraDoc.DocumentObjectModel;
   using MigraDoc.DocumentObjectModel.IO;
   using MigraDoc.Rendering;
   using MigraDoc.Rendering.Forms;
       public partial class Viewer : Form
       {

      private MigraDoc.Rendering.Forms.DocumentPreview _Preview;

      public Viewer()
           {
                  InitializeComponent();

              // Create a new MigraDoc document
                  Document document = Sample.CreateSample();
           
                 string ddl = MigraDoc.DocumentObjectModel.IO.DdlWriter.WriteToString(document);
                  this._Preview.Ddl = ddl;

      }
       }




//Sample.cs
//===================

   using MigraDoc.DocumentObjectModel;
   using System;
   using System.IO;
       public class Sample
       {

      public static Document CreateSample()
           {
                  byte[] _byte = File.ReadAllBytes("c:\\image1.jpg");
                  MemoryStream stream = new MemoryStream(_byte);

             Section section;
                  Paragraph paragraph;

                  // Create a new MigraDoc document
                  Document document = new Document();

                  // Add a section to the document
                  section = document.AddSection();

         paragraph = section.AddParagraph();
                  paragraph = section.AddParagraph();
                  paragraph.AddImage("c:\\image1.jpg");

                  // Add a paragraph to the section
                  paragraph = section.AddParagraph();
         paragraph = section.AddParagraph();
                  paragraph.AddImage(stream);
        
             return document;
           }
       }




//--------------------------using MigraDoc.DocumentObjectModel.dll---------------


//in MigraDoc.DocumentObjectModel.Paragraph.cs:


//added...

    //------------------------------------------------
    /// <summary>
    /// Adds a new Image object
    /// </summary>
    public Image AddImage(Stream stream)
    {
        return this.Elements.AddImage(stream);
    }
    //------------------------------------------------


//in MigraDoc.DocumentObjectModel.ParagraphElements.cs:


//added...

    //----------------------------------------------
    /// <summary>
    /// Adds a new Image from stream.
    /// </summary>
    public Image AddImage(Stream stream)
    {
        Image image = new Image();
        image.Stream = stream;
        Add(image);
        return image;
    }
    //----------------------------------------------


//in MigraDoc.DocumentObjectModel.Internals project

//added NStream.cs class...

//NStream.cs
//==========

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;


namespace MigraDoc.DocumentObjectModel.Internals
{
    internal struct NStream : INullableValue
   {
        public NStream(Stream val)
        {
            this.val = val;
        }

        /// <summary>
        /// Gets or sets the value of the instance.
        /// </summary>
        public Stream Value
        {
            get { return this.val != null ? this.val : null; }
            set { this.val = value; }
        }

        /// <summary>
        /// Gets the value of the instance.
        /// </summary>
        object INullableValue.GetValue()
        {
            return this.Value;
        }

        /// <summary>
        /// Sets the value of the instance.
        /// </summary>
        void INullableValue.SetValue(object value)
        {
            this.val = (Stream)value;
        }

        /// <summary>
        /// Resets this instance,
        /// i.e. IsNull() will return true afterwards.
        /// </summary>
        public void SetNull()
        {
            this.val = null;
        }

        /// <summary>
        /// Determines whether this instance is null (not set).
        /// </summary>
        public bool IsNull
        {
            get { return this.val == null; }
        }

        public static implicit operator NStream(Stream val)
        {
            return new NStream(val);
        }

        public static implicit operator Stream(NStream val)
        {
            return val.Value;
        }

        /// <summary>
        /// Returns a value indicating whether this instance is equal to the specified object.
        /// </summary>
        public override bool Equals(object value)
        {
            if (value is NStream)
                return this == (NStream)value;
            return false;
        }

        public override int GetHashCode()
        {
            return this.val.GetHashCode();
        }

        public static bool operator ==(NStream l, NStream r)
        {
            if (l.IsNull)
                return r.IsNull;
            else if (r.IsNull)
                return false;
            else
                return l.Value == r.Value;
        }

        public static bool operator !=(NStream l, NStream r)
        {
            return !(l == r);
        }

        public static readonly NStream NullValue = new NStream(null);

        Stream val;
}

//------------------------------------------------------------------------------------


//in MigraDoc.DocumentObjectModel.Shapes.Image.cs

//added the followings:

    //----------------------------------------------
    /// <summary>
    /// Initializes a new instance of the Image class from Memory Stream.
    /// </summary>
    public Image(Stream stream)
        : this()
    {
        Stream = stream;
    }
    //----------------------------------------------



    //----------------------------------------------
    /// <summary>
    /// Gets or sets the stream of the image.
    /// </summary>
    public Stream Stream
    {
        get { return this.stream.Value; }
        set { this.stream.Value = value; }
    }
    [DV]
    internal NStream stream = NStream.NullValue;
    //---------------------------------------------


//-----------------FINDING---------------------------------------------------
//CanRead = true
//CanSeek = true
//CanTimeout = false
//CanWrite = true
//Length = 16144
//'stream.ReadTimeout' threw an exception of type 'System.InvalidOperationException'
//'stream.WriteTimeout' threw an exception of type 'System.InvalidOperationException'

//public Image AddImage(Stream stream) , argument stream in new MigraDoc.DocumentObjectModel.Paragraph.cs produced //these exceptions for the image filesize of 16kb.


Top
 Profile  
Reply with quote  
PostPosted: Sun Aug 08, 2010 9:17 am 
Offline
PDFsharp Expert
User avatar

Joined: Wed Dec 09, 2009 8:59 am
Posts: 339
IIRC the preview works with a MDDDL file. This works fine with images added from files.
Make sure images added from a stream persist in MDDDL. That's complicated, that's why MigraDoc doesn't support streams "out of the box".

_________________
Öhmesh Volta ("() => true")
PDFsharp Team Holiday Substitute


Top
 Profile  
Reply with quote  
PostPosted: Tue May 15, 2012 12:55 am 
Offline

Joined: Thu May 10, 2012 11:52 pm
Posts: 7
i tried to implement the logic that author posted here. I got exact same problem as the original post creator:

"'stream.ReadTimeout' threw an exception of type 'System.InvalidOperationException'"

I cannot figure out how to use MDDDL.
Is there any code samples on how to store streams in MDDDL? Preferably for this exact situation. Is it going to work with asp.net?


Top
 Profile  
Reply with quote  
PostPosted: Tue May 15, 2012 9:43 am 
Offline
PDFsharp Guru
User avatar

Joined: Mon Oct 16, 2006 8:16 am
Posts: 3095
Location: Cologne, Germany
kko wrote:
Is there any code samples on how to store streams in MDDDL? Preferably for this exact situation.
You cannot use MDDDL (out of the box) if you add images from streams (using the modification from the first post) to your MigraDoc document.

It should work with ASP.NET since you cannot use the Preview with ASP.NET. You cannot combine images from stream with the Preview.
Using images from streams to create PDF files should work (provided the 3rd party code given in the first post works).

_________________
Regards
Thomas Hoevel
PDFsharp Team


Top
 Profile  
Reply with quote  
PostPosted: Tue May 15, 2012 7:18 pm 
Offline

Joined: Thu May 10, 2012 11:52 pm
Posts: 7
Thomas Hoevel,
Thanks for your response. I tried to write file to the user with response.write it still doesn't work for me.

Here's my code:
Page load event:
Code:
  protected void Page_Load(object sender, EventArgs e)
    {
       
        Document document = new Document();
        document = CreateDocument(document);
        document.UseCmykColor = true;
        const bool unicode = false;
        const PdfFontEmbedding embedding = PdfFontEmbedding.Always;
        PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(unicode, embedding);
        pdfRenderer.Document = document;
        const string filename = "test.pdf";
        pdfRenderer.RenderDocument();
        pdfRenderer.Save(filename);

        // Send PDF to browser
        MemoryStream stream = new MemoryStream();
        pdfRenderer.Save(stream, false);
        Response.Clear();
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-length", stream.Length.ToString());
        Response.AddHeader("content-disposition", "attachment; filename=test.pdf");
        Response.BinaryWrite(stream.ToArray());
        Response.Flush();
        stream.Close();
        Response.End();

    }


Create document:
Code:
    public Document CreateDocument(Document document)
    {
        // Create a new MigraDoc document
        document = new Document();
        document.Info.Title = "test";
        document.Info.Subject = "test";
        document.Info.Author = "test";

        DefineStyles(document);

        CreatePage(document);

        return document;
    }


Define styles:
Code:
void DefineStyles(Document document)
    {
        // Get the predefined style Normal.
        MigraDoc.DocumentObjectModel.Style style = document.Styles["Normal"];
        // Because all styles are derived from Normal, the next line changes the
        // font of the whole document. Or, more exactly, it changes the font of
        // all styles and paragraphs that do not redefine the font.
        style.Font.Name = "Arial";

        style = document.Styles[StyleNames.Header];
        style.ParagraphFormat.AddTabStop("8in", TabAlignment.Right);

        style = document.Styles[StyleNames.Footer];
        style.ParagraphFormat.AddTabStop("8in", TabAlignment.Center);

        // Create a new style called Table based on style Normal
        style = document.Styles.AddStyle("Table", "Normal");
        style.Font.Name = "Arial";
       // style.Font.Name = "Times New Roman";
        style.Font.Size = 10;
        // Create a new style called Reference based on style Normal
        style = document.Styles.AddStyle("Reference", "Normal");
        style.ParagraphFormat.SpaceBefore = "5mm";
        style.ParagraphFormat.SpaceAfter = "5mm";
        style.ParagraphFormat.TabStops.AddTabStop("16cm", TabAlignment.Right);
    }



And finally createpage (Commented where it fails)


Code:
void CreatePage(Document document)
    {
        Section section = document.AddSection();

        //HERE WHERE IT FAILS WITH:
        //'((System.IO.Stream)(stream)).ReadTimeout' threw an exception of type 'System.InvalidOperationException'
        //'((System.IO.Stream)(stream)).WriteTimeout' threw an exception of type 'System.InvalidOperationException'
        byte[] _byte = File.ReadAllBytes("c:\\image1.jpg");
        MemoryStream stream = new MemoryStream(_byte);
        Paragraph paragraph = section.Footers.Primary.AddParagraph();
        paragraph = section.AddParagraph();
        paragraph.AddImage(stream);

        Paragraph header = section.Headers.Primary.AddParagraph();
        header.AddFormattedText("Test",new Font("Arial", 15));
        header.AddLineBreak();
        header.AddFormattedText("Test",new Font("Arial", 8));
        header.Format.Alignment = ParagraphAlignment.Center;

        paragraph.AddText("Page ");
        paragraph.AddPageField();
        paragraph.AddLineBreak();
        paragraph.AddText(DateTime.Now.ToShortDateString());
        paragraph.Format.Alignment = ParagraphAlignment.Right;


        this.addressFrame = section.AddTextFrame();
        this.addressFrame.Height = "3.0cm";
        this.addressFrame.Width = "7.0cm";
        this.addressFrame.Left = ShapePosition.Left;
        this.addressFrame.RelativeHorizontal = RelativeHorizontal.Margin;
        this.addressFrame.Top = "5.0cm";
        this.addressFrame.RelativeVertical = RelativeVertical.Page;


        // Create the item table
        this.table = section.AddTable();
        this.table.Style = "Table";
        this.table.Borders.Color = TableBorder;
        this.table.Borders.Width = 0.25;
        this.table.Borders.Left.Width = 0.5;
        this.table.Borders.Right.Width = 0.5;
        this.table.Rows.LeftIndent = 0;

        // Before you can add a row, you must define the columns
        Column column = this.table.AddColumn("4cm");
        column.Format.Alignment = ParagraphAlignment.Center;

        column = this.table.AddColumn("4cm");
        column.Format.Alignment = ParagraphAlignment.Left;
        column.Format.Font.Bold = true;

        column = this.table.AddColumn("4cm");
        column.Format.Alignment = ParagraphAlignment.Left;

        column = this.table.AddColumn("4cm");
        column.Format.Alignment = ParagraphAlignment.Left;

        // Create the header of the table
        Row row = table.AddRow();
        row.HeadingFormat = true;
        row.Format.Alignment = ParagraphAlignment.Center;
        row.Format.Font.Bold = true;
        row.Shading.Color = TableBlue;
        row.Format.Font.Color = White;
        row.Cells[0].AddParagraph("col1");
        row.Cells[0].Format.Alignment = ParagraphAlignment.Left;
        row.Cells[1].AddParagraph("col2");
        row.Cells[1].Format.Alignment = ParagraphAlignment.Left;
        row.Cells[2].AddParagraph("col3");
        row.Cells[2].Format.Alignment = ParagraphAlignment.Left;
        row.Cells[3].AddParagraph("col4");
        row.Cells[3].Format.Alignment = ParagraphAlignment.Left;
        this.table.SetEdge(0, 0,4, 1, Edge.Box, MigraDoc.DocumentObjectModel.BorderStyle.Single, 0.75, Color.Empty);
    }



Let me know if there's something in my code that can be changed to make it work. the same image works if added directly as a file though.


Top
 Profile  
Reply with quote  
PostPosted: Wed May 16, 2012 8:04 am 
Offline
PDFsharp Guru
User avatar

Joined: Mon Oct 16, 2006 8:16 am
Posts: 3095
Location: Cologne, Germany
Adding images from a stream is an extension of MigraDoc. I don't have time now to investigate this problem.

Does the sample from the first post work?
If so, problem in your code (or MigraDoc modification not applied correctly). If not, problem in their code.

_________________
Regards
Thomas Hoevel
PDFsharp Team


Top
 Profile  
Reply with quote  
PostPosted: Tue Sep 22, 2015 8:01 am 
Offline
PDFsharp Expert
User avatar

Joined: Sat Mar 14, 2015 10:15 am
Posts: 909
Location: CCAA
Hi!

With version 1.50 beta 2, there is a solution for such images - a solution that is compatible with MDDDL and also works with DocumentPreview: pass the image as a string when you call AddImage():
http://pdfsharp.net/wiki/MigraDoc_FilelessImages.ashx
This method applies to MigraDoc only.
With PDFsharp you can create an XImage from a Stream.

_________________
Best regards
Thomas
(Freelance Software Developer with several years of MigraDoc/PDFsharp experience)


Top
 Profile  
Reply with quote  
PostPosted: Wed Oct 21, 2015 4:19 pm 
Offline

Joined: Wed Oct 21, 2015 4:09 pm
Posts: 2
TH-Soft wrote:
Hi!

With version 1.50 beta 2, there is a solution for such images - a solution that is compatible with MDDDL and also works with DocumentPreview: pass the image as a string when you call AddImage():
http://pdfsharp.net/wiki/MigraDoc_FilelessImages.ashx
This method applies to MigraDoc only.
With PDFsharp you can create an XImage from a Stream.

Hello,

I'm trying to implement this solution. My Migradoc version is 1.50.3915.0 I'm storing my image to my DB as a varbinary max, and pulling it back out as a byte array. When I try to use the Addimage..

Code:
byte[] Wordmark = dbReturn[0].image;
string filename = "base64:" + Convert.ToBase64String(Wordmark);
section.AddImage(filename);


When I do this, it adds a gray box that is the correct size of my image to my PDF, but inside the box it says "Image could not be read." My initial image was a .jpg file, uploaded through a web interface to the DB. I am able to pull down the image and save it again, from my DB through my web-interface, so I know the stored image isn't corrupted. Is there something else that I am missing here?

Thanks,
Kevin


Top
 Profile  
Reply with quote  
PostPosted: Wed Oct 21, 2015 6:16 pm 
Offline
PDFsharp Expert
User avatar

Joined: Sat Mar 14, 2015 10:15 am
Posts: 909
Location: CCAA
pezman726 wrote:
Is there something else that I am missing here?
My test code works with JPEG files (WPF build of MigraDoc).

Does it work when you save the byte[] to a file and pass the filename to AddImage()?

_________________
Best regards
Thomas
(Freelance Software Developer with several years of MigraDoc/PDFsharp experience)


Top
 Profile  
Reply with quote  
PostPosted: Wed Oct 21, 2015 6:34 pm 
Offline

Joined: Wed Oct 21, 2015 4:09 pm
Posts: 2
TH-Soft wrote:
pezman726 wrote:
Is there something else that I am missing here?
My test code works with JPEG files (WPF build of MigraDoc).

Does it work when you save the byte[] to a file and pass the filename to AddImage()?


I got it to work! I had previously updated my install to the latest (I think I had v1.3 something...). I went back and uninstalled everything, and installed the GDI version. Now it works!!

Thanks!!

-Kevin


Top
 Profile  
Reply with quote  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 10 posts ] 

All times are UTC


Who is online

Users browsing this forum: Baidu [Spider] and 135 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Search for:
Jump to:  
cron
Privacy Policy, Data Protection Declaration, Impressum
Powered by phpBB® Forum Software © phpBB Group