Friday, 17 April 2015

PDFFileWriter Generate Images in PDF using c#


 Download PDFFileWriter C# class library (DLL)

One Image in PDF Document

Design Page

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="drawimageinpdf.aspx.cs" Inherits="drawimageinpdf"%>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
    </div>
    </form>
</body>

</html>

.CS Page

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using PdfFileWriter;
using System.Diagnostics;
using System.Drawing;

public partial class drawimageinpdf : System.Web.UI.Page
{
    static PdfDocument Document;
    static PdfPage Page;
    static PdfContents Contents;
   
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Test(false, Server.MapPath("~/PdfFiles/abc.pdf"));//Generate Pdf Doc in PdfFiles Folder
    }
    public void Test(Boolean Debug, String FileName)
    {
        Document = new PdfDocument(PaperType.Letter, false, UnitOfMeasure.Inch);
        Document.Debug = Debug;
        Page = new PdfPage(Document);
        Contents = new PdfContents(Page);
 PdfImage Image1 = new PdfImage(Document, Server.MapPath("~/images/Flower.jpg")); //Image to show in Pdf
        Image1.SetImageQuality(50);
        Contents.SaveGraphicsState();
        Contents.Translate(0.00, 1.0);
        ImageSizePos NewSize = Image1.ImageSizePosition(8.27, 9.02, ContentAlignment.MiddleCenter);
        Contents.DrawImage(Image1, NewSize.DeltaX, NewSize.DeltaY, NewSize.Width, NewSize.Height);
        Contents.RestoreGraphicsState();

        Document.CreateFile(FileName);
        Process Proc = new Process();
        Proc.StartInfo = new ProcessStartInfo(FileName);

       //Download Image in Pdf Document
        Response.ClearContent();  //Clears all content output from Buffer Stream
        Response.ClearHeaders(); //Clears all headers from Buffer Stream
        //Adds an HTTP header to the output stream
Response.AddHeader("Content-Disposition", "inline;filename="+ DateTime.Now.ToString("yyyyMMddhhmm")); 
        Response.ContentType = "application/pdf";  //Gets or Sets the HTTP MIME type of the output stream
 //Writes the content of the specified file directory to an HTTP response output stream as a file block
        Response.WriteFile(FileName);
        Response.Flush(); //sends all currently buffered output to the client
        Response.Clear(); //Clears all content output from Buffer Stream
    }
}

  More than One Image in PDF Document

Document = new PdfDocument(8.27, 11.02, UnitOfMeasure.Inch);
            Document.Debug = Debug;

            for (int i = 0; i < dss.Rows.Count; i++) //Load Image Path's Into DataSet
            {
                Page = new PdfPage(Document);
                Contents = new PdfContents(Page);
                string path = Server.MapPath("~/" + dss.Rows[i]["filepath"].ToString());
                PdfImage Image1 = new PdfImage(Document, path);

                Image1.SetImageQuality(50);
                Contents.SaveGraphicsState();
                Contents.Translate(0.00, 1.0);
ImageSizePos NewSize = Image1.ImageSizePosition(8.27, 9.02, ContentAlignment.MiddleCenter);
                Contents.DrawImage(Image1, NewSize.DeltaX, NewSize.DeltaY, NewSize.Width, NewSize.Height);
                Contents.RestoreGraphicsState();
            }
            Document.CreateFile(FileName);
            Process Proc = new Process();

            Proc.StartInfo = new ProcessStartInfo(FileName);


Reference:
http://www.codeproject.com/Articles/570682/PDF-File-Writer-Csharp-Class-Library-Version?rp=/KB/files/570682/PdfFileWriter_dll.zip

Monday, 6 October 2014

Import CSV file with Last Modified DateTime and Specific Name From Folder To SQL Server Using Asp.Net C#



Design Page

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div align="center">
            <asp:Label ID="lblMsg" runat="server" Text="Label" Visible="false" ForeColor="Red"></asp:Label>
        </div>
    </form>
</body>

</html>

.CS File


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using System.Data.OleDb;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            lblMsg.Text = "";
            String Path = Server.MapPath("~/FolderName/");
            var directory = new DirectoryInfo(Path);
            string[] name = new string[] { "Employee", "Emp"};//Import Files With Specific Name
            var fileName = (from f in directory.GetFiles()
                            from n in name
                            where f.Name.Contains(n)
                            orderby f.LastWriteTime descending  //Last Modified Date
                            select f).First();

            string excelPath = Server.MapPath("~/FolderName/") + fileName;

            if (fileName.Extension == ".xls" || fileName.Extension == ".xlsx")
            {
                string conString = string.Empty;
                switch (fileName.Extension)
                {
                    case ".xls": //Excel 97-03
                        conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
                        break;
                    case ".xlsx": //Excel 07 or higher
                        conString = ConfigurationManager.ConnectionStrings["Excel07+ConString"].ConnectionString;
                        break;
                }
                conString = string.Format(conString, excelPath);
                using (OleDbConnection excel_con = new OleDbConnection(conString))
                {
                    excel_con.Open();
                    string sheet1 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["TABLE_NAME"].ToString();

                    DataTable dtExcelData = new DataTable();
                    using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT * FROM [" + sheet1 + "]", excel_con))
                    {
                        oda.Fill(dtExcelData);
                    }
                    excel_con.Close();
                    using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["COMMONConnectionString"].ConnectionString))
                    {
                            for (int i = 0; i < dtExcelData.Rows.Count; i++)
                            {
                                DataRow row = dtExcelData.Rows[i];
                                int columnCount = dtExcelData.Columns.Count;
                                string[] columns = new string[columnCount];
                                for (int j = 0; j < columnCount; j++)
                                {
                                    columns[j] = row[j].ToString();
                                }
                                string sql = "Insert Into TableName(Empid,Name,Email,Salary)";
                                sql += "VALUES('" + columns[0] + "','" + columns[1] + "','" + columns[2] + "','" + columns[3] + "')";
                                SqlCommand cmd = new SqlCommand(sql, con);
                                SqlDataAdapter da = new SqlDataAdapter(cmd);
                                DataSet ds = new DataSet();
                                da.Fill(ds);
                            }
                            lblMsg.Visible = true;
                            lblMsg.Text = "Excel Data Imported To SQL Server Successfully";
                    }
                }
            }
            else
            {
                lblMsg.Visible = true;
                lblMsg.Text = "File Format is Not Supported. Try Again With Excel File Format";
            }
        }
        catch (Exception ex)
        {
            lblMsg.Visible = true;
            lblMsg.Text = ex.Message;
        }
    }
}


 Add In Web.Config File
 
<connectionStrings>
<add name="COMMONConnectionString" connectionString="Data Source=....;Initial Catalog=.....;User ID=sa;Password=123" providerName="System.Data.SqlClient"/>

<add name = "Excel03ConString" connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'"/>

    <add name = "Excel07+ConString" connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}; Extended Properties='Excel 8.0;HDR=YES'"/>
</connectionStrings>