2012-02-08 47 views
3

我在寫一個windows服務,它需要從數據庫中檢索數據,從這些數據構建一個文檔然後傳真。 Tiff似乎是傳真圖像的標準,我知道我可以將Image對象編碼爲tiff。創建文檔圖像

如果我可以通過創建新元素並將元素附加到PdfDocument對象來構建類似於iTextSharp的文檔那樣的圖像對象,那將會很棒。我的傳真文件將是簡單的,但需要這些東西

  • 圍繞文本
  • 的段落添加其他圖片用絕對定位(標識)
  • 現場簡單的兩頁的表/值
  • 水平規則

創建一個HTML文檔是微不足道的,但.Net似乎沒有辦法將HTML呈現給圖像對象。

合意的解決方案可能是BCL中的某種類型的文檔類,它可以呈現給一個圖像對象,我可以從那裏編碼或者某種類型的幫助程序類/庫或圖像包裝程序將這些簡單元素繪製到圖像實例。

兩種解決方案是否存在,或者是否有其他可以考慮的方法?

回答

0

所以我找到了一個解決方案,可以讓我用我需要的功能構建文檔。我最終使用了MigraDoc,儘管它確實沒有iTextSharp那麼優雅。 MigraDoc允許我使用它的XGraphics類從Document對象創建一個System.Drawing.Image對象。

用少數人的MigraDoc例子(我真的希望他們有更好的類庫文件,這是一個很大的缺點,恕我直言)我能創造這樣的

public void CreateNotificationImage(string imagePath, NotificationData data) 
{ 
    // CreateDocument() is my own method where a new doc is created with new data 
    Document doc = CreateDocument(data); 
    doc.DefaultPageSetup.PageFormat = PageFormat.Letter; 

    int page = 1; 
    DocumentRenderer renderer = new DocumentRenderer(doc); 
    renderer.PrepareDocument(); 
    PageInfo pageInfo = renderer.FormattedDocument.GetPageInfo(page); 

    int dpi = 150; 
    int dx = (int)(pageInfo.Width.Inch * dpi); 
    int dy = (int)(pageInfo.Height.Inch * dpi); 
    float scale = dpi/72f; 

    System.Drawing.Image image = new Bitmap(dx, dy, PixelFormat.Format32bppRgb); 

    using (Graphics graphics = Graphics.FromImage(image)) 
    { 
     graphics.Clear(System.Drawing.Color.White); 
     graphics.ScaleTransform(scale, scale); // scale to 72dpi 

     using (XGraphics gfx = XGraphics.FromGraphics(graphics, new XSize(Unit.FromInch(8.5).Point, Unit.FromInch(11).Point))) 
     { 
      renderer.RenderPage(gfx, page); 
      WriteTiffImage(imagePath, image); 
     } 
    }   
} 

WriteTiffImage TIFF文件()是用於將圖像編碼爲TIFF,然後進行最終寫入光盤。

private void WriteTiffImage(string targetPath, System.Drawing.Image image) 
{ 
    Encoder  encoder = Encoder.SaveFlag; 
    ImageCodecInfo tiffInfo = ImageCodecInfo.GetImageEncoders() 
           .Where(e => e.MimeType == "image/tiff") 
           .FirstOrDefault(); 

    EncoderParameters encoderParams = new EncoderParameters(1); 
    encoderParams.Param[0] = new EncoderParameter(encoder, (long)EncoderValue.MultiFrame); 

    image.Save(targetPath, tiffInfo, encoderParams); 

    // close file 
    encoderParams.Param[0] = new EncoderParameter(encoder, (long)EncoderValue.Flush); 
    image.SaveAdd(encoderParams); 
} 

我可能甚至不需要做縮放,但它是在這個例子中,併爲我想要完成的工作做得很好。