Resmi PDF e çevirmek Etiketli Yazılar

C# – Word-Excel-Images to PDF

Word ve Excel dosyalarını PDF formatına çevirmek için aşağıdaki uygulamayı kullanabilirsininiz.

Derleyebilmeniz için,

Microsoft Save as PDF Add-in for the 2007 Office release

eklentisini kurmanız gerekiyor.

Not: Aşağıdaki kodlar ile; Localhost test de sorun yaşamıyor IIS üzerinden girişte proplem oluyorsa, sistemi aşağıdaki şekilde yapılandırmalısınız.

Çalıştır -> DCOMCNFG -> Companents Service -> My Computer -> DCOM Config -> Microsft Excel Application -> Sağ tık -> Properties -> Identity -> The İneractive User seçilmelidir.
Benzer İşlemin Microsoft Office Word içinde tekrarlanması gerekir.
(Sorun yaşarsanız web config de imporsonate kullanıp user ve pass belirtip  dcom da  Identity tabında da bu kullanıyı belirtirseniz sorun kalmayacaktır.)

 

//Default.aspx.cs
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        string kokdizin = @"D:\Applications\Fax\temp";
        Library.SendFileToClient(Page, Library.DocToPDF(Library.Upload(file1, kokdizin)), "pdf");
    }
}

 

//Library.cs

using System.Collections.Generic;
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Data;
using System.Text;
using Microsoft.Office.Interop.Word;
using Microsoft.Office.Interop.Excel;
using iTextSharp;
using System.Data.OleDb;
using DevExpress.Web.ASPxGridView;

public class Library
{
   public static string DocToPDF(string dosyayolu)
    {
        string pdfyolu = "";
        if (dosyayolu.Contains(".doc"))
        {
            pdfyolu = dosyayolu.Replace("docx", "pdf").Replace("doc", "pdf");
            Library.Word2PDF(dosyayolu, dosyayolu.Replace("docx", "pdf").Replace("doc", "pdf"));
        }
        else if (dosyayolu.Contains(".xls"))
        {
            pdfyolu = dosyayolu.Replace("xlsx", "pdf").Replace("xls", "pdf");
            Library.Excel2PDF(dosyayolu, pdfyolu);
        }
        else if (dosyayolu.Contains(".jpg") || dosyayolu.Contains(".bmp") || dosyayolu.Contains(".png") )
        {
            pdfyolu = dosyayolu.Replace("jpg", "pdf").Replace("bmp", "pdf").Replace("png", "pdf");
            Library.IMAGE2PDF(dosyayolu, pdfyolu);
        }
        return pdfyolu;
    }

   public static void Word2PDF(object Source, object Target)
   {
           object Unknown = Type.Missing;
           object missing = Type.Missing;
           object isVisible = Type.Missing;
           object isReadonly = Type.Missing;
           //Word Uygulaması tanımla
           Microsoft.Office.Interop.Word.ApplicationClass MSdoc=null;
           if (MSdoc == null) MSdoc = new Microsoft.Office.Interop.Word.ApplicationClass();
        try
         {
           MSdoc.Visible = false;
           //Aç
           Microsoft.Office.Interop.Word.Document oDoc = MSdoc.Documents.Open(ref Source, ref isReadonly, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown,
           ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref isVisible, ref Unknown, ref Unknown, ref Unknown, ref Unknown);
           MSdoc.WindowState = Microsoft.Office.Interop.Word.WdWindowState.wdWindowStateMinimize;
           if (oDoc != null)
           {   //Kaydet
               object format = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF;
               oDoc.SaveAs(ref Target, ref format, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown,
               ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown);
           }
      }
       catch 
       {
            //Çıkış
            MSdoc.Quit(ref Unknown, ref Unknown, ref Unknown);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(MSdoc);
       } 
       finally 
       { 
           //Çıkış
            MSdoc.Quit(ref Unknown, ref Unknown, ref Unknown);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(MSdoc);
       }
   }

   public static void Excel2PDF(string Source, string Target)
   {
       Microsoft.Office.Interop.Excel.ApplicationClass excelApplication = new Microsoft.Office.Interop.Excel.ApplicationClass();
       Workbook excelWorkBook = null;
       //
       string paramSourceBookPath = Source; object paramMissing = Type.Missing;
       //
       string paramExportFilePath = Target;
       XlFixedFormatType paramExportFormat = XlFixedFormatType.xlTypePDF;
       XlFixedFormatQuality paramExportQuality = XlFixedFormatQuality.xlQualityStandard;
       bool paramOpenAfterPublish = false; bool paramIncludeDocProps = true; bool paramIgnorePrintAreas = true;
       object paramFromPage = Type.Missing; object paramToPage = Type.Missing;
       try
       {
           excelWorkBook = excelApplication.Workbooks.Open(paramSourceBookPath,
           paramMissing, paramMissing, paramMissing, paramMissing, paramMissing, paramMissing, paramMissing, paramMissing,
           paramMissing, paramMissing, paramMissing, paramMissing, paramMissing, paramMissing);
           if (excelWorkBook != null) excelWorkBook.ExportAsFixedFormat(paramExportFormat, paramExportFilePath, paramExportQuality,
          paramIncludeDocProps, paramIgnorePrintAreas, paramFromPage, paramToPage, paramOpenAfterPublish, paramMissing);
       }
       catch { }
       finally
       {
           if (excelWorkBook != null) { excelWorkBook.Close(false, paramMissing, paramMissing); excelWorkBook = null; }
           if (excelApplication != null) { excelApplication.Quit(); excelApplication = null; }
           GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers();
       }  
   }

   public static void IMAGE2PDF(string Source, string Target)
   {
       iTextSharp.text.Document document = new iTextSharp.text.Document();
       using (var stream = new FileStream(Target, FileMode.Create, FileAccess.Write, FileShare.None))
       {
           iTextSharp.text.pdf.PdfWriter.GetInstance(document, stream);
           document.Open();
           using (var imageStream = new FileStream(Source, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
           {
               var image = iTextSharp.text.Image.GetInstance(imageStream);
               document.Add(image);
           }
           document.Close();
       }
   }

   public static string Upload(FileUpload gozatadi, string anadizin)
   {
       gozatadi.SaveAs(anadizin + "\\" + Path.GetFileName(gozatadi.FileName));
       return anadizin + "\\"+ Path.GetFileName(gozatadi.FileName);
    }

   public static void SendFileToClient(System.Web.UI.Page sayfa, string path, string tur)
    {
        byte[] content;System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Open);
        try
        { content = new byte[fs.Length]; fs.Read(content, 0, content.Length); }  finally   {fs.Close();  }
        sayfa.Response.Clear();sayfa.Response.ClearHeaders(); sayfa.Response.ClearContent();
        sayfa.Response.ContentEncoding = System.Text.Encoding.GetEncoding("ISO-8859-9");
        sayfa.Response.ContentType = "application/" + tur;
        sayfa.Response.Charset = "windows-1254";
        sayfa.Response.AddHeader("Content-Length", content.Length.ToString());
        sayfa.Response.AddHeader("content-disposition", "attachment; filename=\"" + sayfa.Server.UrlPathEncode(System.IO.Path.GetFileName(path)) + "\"");
        sayfa.Response.BinaryWrite(content);
        sayfa.Response.Flush();
        sayfa.Response.End();
    }
}