2017-04-25 66 views
-1

如何将jpg/png/txt或任何文件格式转换为使用mvc c#的pdf。 下面是代码:将jpg/png/txt或任何文件格式转换为pdf使用mvc5

public ActionResult SaveProfileDocument(string code) 
     { 
      bool isSavedSuccessfully = true; 
      string fName = ""; 
      string _documentname = String.Empty; 

      try 
      { 
       foreach (string fileName in Request.Files) 
       { 
        HttpPostedFileBase file = Request.Files[fileName]; 
        //Save file content goes here 
        fName = file.FileName; 
        if (file != null && file.ContentLength > 0) 
        { 

         var originalDirectory = new DirectoryInfo(string.Format("{0}Documents\\Profile\\" + code, Server.MapPath(@"\"))); 

         string pathString = System.IO.Path.Combine(originalDirectory.ToString()); 

         var fileName1 = Path.GetFileName(file.FileName); 

         bool isExists = System.IO.Directory.Exists(pathString); 

         if (!isExists) 
          System.IO.Directory.CreateDirectory(pathString); 

         _documentname=fName; 

         var path = string.Format("{0}\\{1}", pathString, file.FileName); 
         if (System.IO.File.Exists(path)) { 
          _documentname=Guid.NewGuid()+"_"+file.FileName; 

          var path2 = string.Format("{0}\\{1}", pathString,_documentname); 
          file.SaveAs(path2); 
         } 
         else { 
          file.SaveAs(path); 
         } 

        } 

       } 

      } 
      catch (Exception ex) 
      { 
       isSavedSuccessfully = false; 
      } 


      if (isSavedSuccessfully) 
      { 
       return Json(new { Message = fName, documentname = _documentname }); 
      } 
      else 
      { 
       return Json(new { Message = "Error in saving file", documentname=""}); 
      } 
     } 

在上面的代码中,我很节省file.but 在这里,我需要转换的文件,然后保存。

因此对于转换我需要一个单独的类或方法在这里只调用该方法。

事情是,虽然上传文件时间需要转换PDF任何文件转换为PDF。并保存在文件夹或其他。

+0

我不知道你的问题是什么。你坚持什么? – mason

+0

我需要将jpg格式文件转换为pdf,使用c# –

+0

您不会将JPG文件转换为PDF。 JPG是一种图像格式。 PDF是一种文档格式。你可以创建一个PDF,然后插入一个JPG。您可能需要一个能够生成PDF的库。我建议你研究并找到一个可以和.NET一起工作并阅读它的文档。 – mason

回答

0

无法将图像文件转换为PDF。您可以创建一个PDF文件和图像文件添加到它:

string pdfpath = Server.MapPath("PDFs"); 
string imagepath = Server.MapPath("Images"); 
Document doc = new Document(); 
try 
{ 
    PdfWriter.GetInstance(doc, new FileStream(pdfpath + "/Images.pdf", FileMode.Create)); 
    doc.Open(); 

    doc.Add(new Paragraph("GIF")); 
    Image gif = Image.GetInstance(imagepath + "/mikesdotnetting.gif"); 
    doc.Add(gif); 
} 
catch (Exception ex) 
{ 
    //Log error; 
} 
finally 
{ 
    doc.Close(); 
} 

我在这里是指:

https://www.mikesdotnetting.com/article/87/itextsharp-working-with-images

相关问题