ImageMagick.NET只在ASP.NET MVC中呈现PDF文件的第一页?

时间:2016-11-30 19:55:10

标签: c# asp.net-mvc pdf

我试图将PDF文件转换为图片,但我只能转换第一页。 继承人我所拥有的。 代码背后:

 [HttpPost]
        public ActionResult UploadPdf(HttpPostedFileBase file)
        {
            MemoryStream target = new MemoryStream();
            file.InputStream.CopyTo(target);
            byte[] data = target.ToArray();


            MagickReadSettings settings = new MagickReadSettings();
            settings.Density = new Density(300, 300);
            MemoryStream convertedFile = new MemoryStream();
            List<ImageModel> model = new List<ImageModel>();
            using (MagickImageCollection images = new MagickImageCollection())
            {
                images.Read(data,settings); // Read PDF file
                foreach (MagickImage image in images)
                {
                    ImageModel innerModle = new ImageModel();
                    image.Write(convertedFile, MagickFormat.Png);
                    byte[] data2 = convertedFile.ToArray();
                    innerModle.Image = data2;
                    model.Add(innerModle);                     
               }                 
            }                         
            return View(model);
        }

查看型号:

 public class ImageModel
    {
        public byte[] Image{ get; set; }
    }

查看:

@model List<DocumentViewerPoc.Models.ImageModel>
@foreach (var item in Model)
{
    var base64 = Convert.ToBase64String(item.Image);
    var imgSrc = String.Format("data:image/gif;base64,{0}", base64);
    <img src="@imgSrc" />
}

我尝试使用convertedFile.Flush();,但我没有这样做。我在这里失踪了什么? 谢谢:))

1 个答案:

答案 0 :(得分:0)

在下面更改您的代码:

    [HttpPost]
    public ActionResult UploadPdf(HttpPostedFileBase file)
    {
        MemoryStream target = new MemoryStream();
        file.InputStream.CopyTo(target);
        byte[] data = target.ToArray();


        MagickReadSettings settings = new MagickReadSettings();
        settings.Density = new Density(300, 300);

        List<ImageModel> model = new List<ImageModel>();
        using (MagickImageCollection images = new MagickImageCollection())
        {
            images.Read(data,settings); // Read PDF file
            foreach (MagickImage image in images)
            {
                MemoryStream convertedFile = new MemoryStream();
                ImageModel innerModle = new ImageModel();
                image.Write(convertedFile, MagickFormat.Png);
                byte[] data2 = convertedFile.ToArray();
                innerModle.Image = data2;
                model.Add(innerModle);                     
           }                 
        }                         
        return View(model);
    }