Friday, 29 December 2017

Copy all the documents from site to local directory

<button type="button"  onclick="do_dl();">Test downloading 3 text files.</button>


<script>
 SP.SOD.executeFunc('sp.js', 'SP.ClientContext');
var siteurl="https://****.sharepoint.com/sites/DEV/";
function GetDocuments(success,failure) {
debugger;
    $.ajax({
        url: siteurl + "/_api/web/lists/getbytitle('Documents')/items?$select=EncodedAbsUrl&$expand=File",
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
        success: function (data) {
           success(data.d.results);   
        },
        error: function (data) {
        debugger;
            failure(data);         
        }     
    });
}
function GetDocumentsSuccess(arrayname)
{
debugger;
alert("Success");

       download_files([
      { download: arrayname[0].EncodedAbsUrl, filename: arrayname[0].File.Name},
      { download: arrayname[1].EncodedAbsUrl, filename: arrayname[1].File.Name},
      { download: arrayname[2].EncodedAbsUrl, filename: arrayname[2].File.Name},
      { download: arrayname[3].EncodedAbsUrl, filename: arrayname[2].File.Name},
      { download: arrayname[4].EncodedAbsUrl, filename: arrayname[2].File.Name},
      { download: arrayname[5].EncodedAbsUrl, filename: arrayname[2].File.Name},
    ]);                     
}
function GetDocumentsFailure()
{
alert("Failure");
}


function download_files(files) {
debugger;
  function download_next(i) {
  debugger;
    if (i >= files.length) {
      return;
    }
    var a = document.createElement('a');
    a.href = files[i].download;
    a.target = '_parent';
    // Use a.download if available, it prevents plugins from opening.
    if ('download' in a) {
      a.download = files[i].filename;
    }
    // Add a to the doc for click to work.
    (document.body || document.documentElement).appendChild(a);
    if (a.click) {
      a.click(); // The click method is supported by most browsers.
    } else {
      $(a).click(); // Backup using jquery
    }
    // Delete the temporary link.
    a.parentNode.removeChild(a);
    // Download the next file with a small timeout. The timeout is necessary
    // for IE, which will otherwise only download the first file.
    setTimeout(function() {
      download_next(i + 1);
    }, 500);
  }
  // Initiate the first download.
  download_next(0);
}

</script>

Thursday, 28 December 2017

SharePoint 2013 App Model: How to view list, list settings inside app

Tip#1: SharePoint hosted app
Microsoft bring with new development approach “app” framework in SharePoint 2013 and whenever a new version of SharePoint brings a new development approach, developer often face some internal challenges.
In SharePoint 2013 each app create a new “app web” inside the “host web”. SharePoint App web does not own setting page or any navigation to traverse to list, list settings.
In this blog post I will provide you some useful tips about app model
View List and List Settings: In normal scenario when we create any list using SharePoint host apps, there is no default option to see the list and go to list settings



I have created the list with Name “QuickStatus” but there is no option for directly go to the list and view the content.
Conclusion:
  • In order to go to the list directly type the name of the list after your app name
Example: “http://app-guid.contosoapps.com/sites/sphostedapps/<AppName>/Lists/QuickStatus/Allitems.aspx”


  • To View List Settings Click on the “Modify View” from the ribbon. You will see the “Settings” link on the top as shown in below screen. Click on the link and you will redirect to setting page.





You  can also directly open in the browser by specifying the URL as shown in below screen by specifying the list id.


Friday, 15 December 2017

itextsharp error owner password reqired while opening pdf using c#


If we add the below line problem will solve
PdfReader.unethicalreading = true;

add page number to pdf footer using itextsharp

Namespaces
You will need to import the following namespaces.
C#
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
 
VB.Net
Imports System.IO
Imports iTextSharp.text
Imports iTextSharp.text.pdf
 
 
Adding Page numbers to existing PDF
The PDF file to which the page numbers needs to be added is read into a Byte array from the disk. Then the byte array is read into a PdfReader object and a loop is executed over the pages of the PDF and the page number is added to each page using the PdfStamper class.
Finally the MemoryStream is saved to disk as PDF file.
C#
protected void AddPageNumber(object sender, EventArgs e)
{
    byte[] bytes = File.ReadAllBytes(@"D:\PDFs\Test.pdf");
    Font blackFont = FontFactory.GetFont("Arial", 12, Font.NORMAL, BaseColor.BLACK);
    using (MemoryStream stream = new MemoryStream())
    {
        PdfReader reader = new PdfReader(bytes);
        using (PdfStamper stamper = new PdfStamper(reader, stream))
        {
            int pages = reader.NumberOfPages;
            for (int i = 1; i <= pages; i++)
            {
                ColumnText.ShowTextAligned(stamper.GetUnderContent(i), Element.ALIGN_RIGHT, new Phrase(i.ToString(), blackFont), 568f, 15f, 0);
            }
        }
        bytes = stream.ToArray();
    }
    File.WriteAllBytes(@"D:\PDFs\Test_1.pdf", bytes);
}
 
VB.Net
Protected Sub AddPageNumber(sender As Object, e As EventArgs)
    Dim bytes As Byte() = File.ReadAllBytes("D:\PDFs\Test.pdf")
    Dim blackFont As Font = FontFactory.GetFont("Arial", 12, Font.NORMAL, BaseColor.BLACK)
    Using stream As New MemoryStream()
        Dim reader As New PdfReader(bytes)
        Using stamper As New PdfStamper(reader, stream)
            Dim pages As Integer = reader.NumberOfPages
            For i As Integer = 1 To pages
                ColumnText.ShowTextAligned(stamper.GetUnderContent(i), Element.ALIGN_RIGHT, New Phrase(i.ToString(), blackFont), 568.0F, 15.0F, 0)
            Next
        End Using
        bytes = stream.ToArray()
    End Using
    File.WriteAllBytes("D:\PDFs\Test_1.pdf", bytes)
End Sub

Tuesday, 12 December 2017

Export gridview to pdf in asp.net

Export Gridview to PDF in asp.net



Step 1: Create an asp.net web application project. 

Step 2: Drag and drop a gridview control and a button control on webform1.aspx. Autoformat the gridview control to use "BrownSugar" scheme. Double click on the button control, to generate click event handler method.

At this point the HTML on webform1.aspx should be as shown below.
<asp:GridView ID="GridView1" runat="server" BackColor="#DEBA84" 
    BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" 
    CellPadding="3" CellSpacing="2">
    <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
    <HeaderStyle BackColor="#A55129" Font-Bold="True" 
        ForeColor="White" />
    <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
    <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
    <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" 
        ForeColor="White" />
    <SortedAscendingCellStyle BackColor="#FFF1D4" />
    <SortedAscendingHeaderStyle BackColor="#B95C30" />
    <SortedDescendingCellStyle BackColor="#F1E5CE" />
    <SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>
<asp:Button ID="Button1" runat="server" Text="Button" 
onclick="Button1_Click" />

Step 3: To generate PDF documents we will be using open source assembly - iTextSharp.dll. This assembly can be downloaded from http://sourceforge.net/projects/itextsharp.

After you download the assembly, add a reference to it, from your web application.

a) In Solution Explorer, right click on the "References" folder and select "Add Reference"
b) Browse to the folder where you have downloaded the assembly and Click OK.

Step 4: Add the following "USING" statements, in your code-behind 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.SqlClient;
using System.Data;
using System.Configuration;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;

Step 5: Copy and paste the following code. The code is well commented and is self-explanatory.
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindGridViewData();
    }
}

// ADO.NET code to retrieve data from database
private void BindGridViewData()
{
    string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
    using (SqlConnection con = new SqlConnection(CS))
    {
        SqlDataAdapter da = new SqlDataAdapter("Select * from tblEmployee", con);
        DataSet ds = new DataSet();
        da.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
    }
}

protected void Button1_Click(object sender, EventArgs e)
{
    int columnsCount = GridView1.HeaderRow.Cells.Count;
    // Create the PDF Table specifying the number of columns
    PdfPTable pdfTable = new PdfPTable(columnsCount);

    // Loop thru each cell in GrdiView header row
    foreach(TableCell gridViewHeaderCell in GridView1.HeaderRow.Cells)
    {
        // Create the Font Object for PDF document
        Font font = new Font();
        // Set the font color to GridView header row font color
        font.Color = new BaseColor(GridView1.HeaderStyle.ForeColor);

        // Create the PDF cell, specifying the text and font
        PdfPCell pdfCell = new PdfPCell(new Phrase(gridViewHeaderCell.Text, font));

        // Set the PDF cell backgroundcolor to GridView header row BackgroundColor color
        pdfCell.BackgroundColor = new BaseColor(GridView1.HeaderStyle.BackColor);

        // Add the cell to PDF table
        pdfTable.AddCell(pdfCell);
    }

    // Loop thru each datarow in GrdiView
    foreach (GridViewRow gridViewRow in GridView1.Rows)
    {
        if (gridViewRow.RowType == DataControlRowType.DataRow)
        {
            // Loop thru each cell in GrdiView data row
            foreach (TableCell gridViewCell in gridViewRow.Cells)
            {
                Font font = new Font();
                font.Color = new BaseColor(GridView1.RowStyle.ForeColor);

                PdfPCell pdfCell = new PdfPCell(new Phrase(gridViewCell.Text, font));

                pdfCell.BackgroundColor = new BaseColor(GridView1.RowStyle.BackColor);

                pdfTable.AddCell(pdfCell);
            }
        }
    }

    // Create the PDF document specifying page size and margins
    Document pdfDocument = new Document(PageSize.A4, 10f, 10f, 10f, 10f);
    
    PdfWriter.GetInstance(pdfDocument, Response.OutputStream);

    pdfDocument.Open();
    pdfDocument.Add(pdfTable);
    pdfDocument.Close();

    Response.ContentType = "application/pdf";
    Response.AppendHeader("content-disposition", 
        "attachment;filename=Employees.pdf");
    Response.Write(pdfDocument);
    Response.Flush();
    Response.End();
}
At this point, run the application and click on the button. The data gets exported to PDFas expected. If you are using Google chrome as your browser, you may get a browser warning stating - this type of file can harm your computer do you want to keep Employees.pdf anyway? This is a know issue with Google chrome. Internet explorer, works fine. 



Refer this link:

http://csharp-video-tutorials.blogspot.in/2013/04/export-gridview-to-pdf-in-aspnet-part-58.html

Wednesday, 29 November 2017

convert-word-excel-pptx-to-pdf and merge all pdf files in to one pdf

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Collections;
using msExcel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop.Word;
using Microsoft.Office.Interop.PowerPoint;
using Microsoft.Office.Core;
namespace ConsoleApplication1
{
public class Program
{
public static object missing = System.Reflection.Missing.Value;
private static string sourcefolder;
private static string destinationfile;
private static IList fileList = new ArrayList();
public string SourceFolder
{
get { return sourcefolder; }
set { sourcefolder = value; }
}
public string DestinationFile
{
get { return destinationfile; }
set { destinationfile = value; }
}
public static void Main(string[] args)
{
string [] array1=Directory.GetFiles(“D:\\Test”);
for(int i=0;i<array1.Length;i++)
{
if(array1[i].Contains(“.docx”))
{
ConvertWordToPdf(array1[i],array1[i].Substring(array1[i].LastIndexOf(“\\”)+1));
}
else if (array1[i].Contains(“.xlsx”))
{
ConvertExcelToPdf(array1[i], array1[i].Substring(0, array1[i].LastIndexOf(“\\”)));
}
else if (array1[i].Contains(“.pptx”))
{
ConvertPPTXToPDF(array1[i]);
}
}
Execute();
}
public static void AddFile(string pathnname)
{
fileList.Add(pathnname);
}
public static void Execute()
{
MergeDocs();
}
public static void MergeDocs()
{
//Step 1: Create a Docuement-Object
iTextSharp.text.Document document = new iTextSharp.text.Document();
try
{
//Step 2: we create a writer that listens to the document
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(“D:\\Test1\\Final.pdf”, FileMode.Create));
//Step 3: Open the document
document.Open();
PdfContentByte cb = writer.DirectContent; PdfImportedPage page;
int n = 0;
int rotation = 0;
string[] array2= Directory.GetFiles(“D:\\Test”);
for(int i=0;i<array2.Length;i++)
{
if(array2[i].Contains(“.pdf”))
{
AddFile(array2[i]);
}
}
//Loops for each file that has been listed
foreach (string filename in fileList)
{
//The current file path
string filePath = sourcefolder + filename;
// we create a reader for the document
PdfReader reader = new PdfReader(filePath);
//Gets the number of pages to process
n = reader.NumberOfPages; int i = 0;
while (i < n)
{
i++; document.SetPageSize(reader.GetPageSizeWithRotation(1));
document.NewPage();
//Insert to Destination on the first page
if (i == 1)
{
Chunk fileRef = new Chunk(” “);
fileRef.SetLocalDestination(filename); document.Add(fileRef);
}
page = writer.GetImportedPage(reader, i);
rotation = reader.GetPageRotation(i);
if (rotation == 90 || rotation == 270)
{ cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height); }
else
{
cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
}
}
}
catch (Exception e) { throw e; }
finally { document.Close(); }
}
public static void ConvertExcelToPdf(string excelFileIn, string pdfFileOut)
{
msExcel.Application excel = new msExcel.Application();
try
{
excel.Visible = false;
excel.ScreenUpdating = false;
excel.DisplayAlerts = false;
FileInfo excelFile = new FileInfo(excelFileIn);
string filename = excelFile.FullName;
msExcel.Workbook wbk = excel.Workbooks.Open(filename, missing,
missing, missing, missing, missing, missing,
missing, missing, missing, missing, missing,
missing, missing, missing);
wbk.Activate();
object outputFileName = wbk.FullName.Replace(“.xslx”, “.pdf”); ;
msExcel.XlFixedFormatType fileFormat = msExcel.XlFixedFormatType.xlTypePDF;
// Save document into PDF Format
wbk.ExportAsFixedFormat(fileFormat, outputFileName,
missing, missing, missing,
missing, missing, missing,
missing);
object saveChanges = msExcel.XlSaveAction.xlDoNotSaveChanges;
((msExcel._Workbook)wbk).Close(saveChanges, missing, missing);
wbk = null;
}
catch (Exception e)
{
}
finally
{
((msExcel._Application)excel).Quit();
excel = null;
}
}
#region Converting word to PDF
// C# doesn’t have optional arguments so we’ll need a dummy value
// object oMissing = System.Reflection.Missing.Value;
public static void ConvertWordToPdf(String FilePath,String FileName)
{
Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
try
{
// Get a Word file
FileInfo wordFile = new FileInfo((FileName));
word.Visible = false;
word.ScreenUpdating = false;
// Cast as Object for word Open method
Object filename = (Object)FilePath;
//object filename = (Object)wordFile.FullName;
// Use the dummy value as a placeholder for optional arguments
Microsoft.Office.Interop.Word.Document doc = word.Documents.Open(ref filename, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing);
doc.Activate();
object outputFileName = FilePath.Replace(“.docx”, “.pdf”);
object fileFormat = WdSaveFormat.wdFormatPDF;
// Save document into PDF Format
doc.SaveAs(ref outputFileName,
ref fileFormat, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing);
// Close the Word document, but leave the Word application open.
// doc has to be cast to type _Document so that it will find the
// correct Close method.
object saveChanges = WdSaveOptions.wdDoNotSaveChanges;
((_Document)doc).Close(ref saveChanges, ref missing, ref missing);
doc = null;
// word has to be cast to type _Application so that it will find
// the correct Quit method.
((Microsoft.Office.Interop.Word._Application)word).Quit(ref missing, ref missing, ref missing);
word = null;
}
catch (Exception e)
{
}
#endregion
}
public static void ConvertPPTXToPDF(string FileName)
{
Microsoft.Office.Interop.PowerPoint.Application app = new Microsoft.Office.Interop.PowerPoint.Application();
string sourcePptx = FileName;
string targetPpt = sourcePptx.Replace(“.pptx”, “.pdf”);
object missing = Type.Missing;
Microsoft.Office.Interop.PowerPoint.Presentation pptx = app.Presentations.Open(sourcePptx, MsoTriState.msoFalse, MsoTriState.msoTrue, MsoTriState.msoFalse);
pptx.SaveAs(targetPpt, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPDF, MsoTriState.msoTrue);
app.Quit();
}
}
}

Refer

How to get the value from web.config(if any value assign as static Key)

Web.Config File:   <appSettings>     <add key="DomainName" value="PW" />     </appSettings> Cl...