【问题标题】:C# WPF System.Drawing.Image to System.Windows.Media.Imaging.BitmapSourceC# WPF System.Drawing.Image 到 System.Windows.Media.Imaging.BitmapSource
【发布时间】:2015-09-28 11:30:50
【问题描述】:

我使用库 spire.pdf 将 pdf 文件转换为图片,通过文档中提供的代码来完成。生成一个 PDF 文件到图像,因为他想让它们打印,而 PDF 文件本身不能打印(我的意思是打印机)

 public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();


            Spire.Pdf.PdfDocument pdf = new PdfDocument();
            pdf.LoadFromFile("sample.pdf");

            BitmapSource source;
            Bitmap bmp;

            for (int i = 1; i < pdf.Pages.Count+1; i++)
            {
                source = pdf.SaveAsImage(i);
                bmp = SourceToBitmap(source);
                bmp.Save(string.Format("result-{0}.png", i), ImageFormat.Png);
            }
        }

        private Bitmap SourceToBitmap(BitmapSource source)
        {
            Bitmap bmp;
            using (MemoryStream ms = new MemoryStream())
            {
                PngBitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(source));
                encoder.Save(ms);
                bmp = new Bitmap(ms);
            }
            return bmp;
        }
    }

我的包括:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Spire.Pdf;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Media.Imaging;
using System.IO;

但我收到一个错误 source = pdf.SaveAsImage(i);

Error   1   Cannot implicitly convert type 'System.Drawing.Image' to 'System.Windows.Media.Imaging.BitmapSource'    c:\users\łukasz\documents\visual studio 2013\Projects\WpfApplication5\WpfApplication5\MainWindow.xaml.cs    39  26  WpfApplication5

【问题讨论】:

    标签: c# wpf pdf


    【解决方案1】:

    显然PdfDocument.SaveAsImage 返回一个System.Drawing.Image,所以你不需要做任何 WPF 到 WinForms 位图的转换。

    这就足够了:

    var source = pdf.SaveAsImage(i);
    source.Save(string.Format("result-{0}.png", i), ImageFormat.Png);
    

    【讨论】:

    • 谢谢,它有效!还有另一种打印pdf文件的方法吗?我必须将它们转换为图像?
    猜你喜欢
    • 2011-04-14
    • 2016-06-02
    • 1970-01-01
    • 2023-04-02
    • 2022-11-18
    • 2012-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多