Test your technical skills online, appear in Virtual Interview and be ready for job!
Twitter Twitter LinkedIn YouTube Google
Be Interview ready ! | Search
Make friends on DotNetFunda.com and expand your network!
Winners

Win Prizes

Announcements
Like us on Facebook
Sponsor
Top Blogs Author
Sun, 20-Apr-2014 Authors
All Time Authors
Samirbhogayta
9750
Satyapriyanayak
7575
Jvprabhusanthi
6150

Latest members | More ...


(Statistics delayed by 5 minutes)

How to Save PDF File by PDF Viewer with C#, VB.NET

Lacy
Posted by Lacy under C# on 6/3/2012 9:47:03 PM | Points: 75 | Views : 5119 | Status : [Member]

Why Save PDF File by PDF Viewer?

Both PDF and PDF Viewer can save a PDF file. The main difference is that people cannot view that PDF file when save a PDF document by PDF. While using PDF Viewer, you can save any PDF file from your system as well as open and view it in Windows Forms. Furthermore, tasks such as print, zoom, page the PDF document all can be realize by PDF Viewer. Today, I want to share a method to save a PDF file by Spire. PDFViewer with C#, VB.NET.

How to Save PDF file by PDF Viewer with C#, VB.NET

Spire.PDFViewer for .NET is a powerful PDF Viewer component. It allows developers to load PDF document from stream, file and byte array. Spire.PDFViewer is available on viewing PDF/A-1B, PDF/X1A and enables to open and read encrypted PDF files. Please see the below procedure.


Step1. Create a new project.
  1. Create a new project in Windows Forms Application.
  2. Set the target Framework to be .NET in Properties of this project to be .NET Framework 2 or above.

Step2. Add reference and Set up the Form.

  1. Add Spire.PDFViewer Form dll as reference from Spire.PDFViewer.
  2. Add a toolScript and pdfDocumentViewer in the default Form" Form1".
  3. Add three buttons and a ComboBox in Form1 from toolScript dropdown list.
  4. Set the properties of three buttons and ComboBox as below.
Tools                               Properties                                 As
toolStripButton1           Name                                BtnOpen
                                DisplayStyle                       Text
                                    Text                                  Open     
toolStripButton2           Name                                BtnSave
                                DisplayStyle                        Text
                                    Text                                  Save
toolScriptButton3          Name                                BtnSaveStream
                                DisplayStyle                       Text
                                    Text                                 SaveStream
ComboBox                   Name                               comBoxPages
                                DropDownStyle                   DropDownList
pdfDocumentViewer      Name                                pdfDocumentViewer1 
                                Dock                                 Fill
                                Text                                 pdfDocumentViewer1         

Step3. Save PDF file by PDF Viewer.

1.      Add below namespaces at the top of the method.

C# Code:
using System.IO;
using Spire.PdfViewer.Forms;
VB.NET Code:
Imports System.IO
Imports Spire.PdfViewer.Forms

2.     Load PDF file from system and open it. This step allows you to choose a PDF Document directly from system in a dialog box.
C# Code:
        private void Form1_Load(object sender, EventArgs e)
        {
        }
        private void BtnOpen_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "PDF document (*.pdf)|*.pdf";
            DialogResult result = dialog.ShowDialog();
            if (result == DialogResult.OK)
            {
                try
                {
                    string pdfFile = dialog.FileName;
                    this.pdfDocumentViewer1.LoadFromFile(pdfFile);
                }
                catch (Exception exe)
                {
                    MessageBox.Show(exe.Message, "Spire.PdfViewer Demo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
VB.NET Code:
               Private Sub Form1_Load(sender As Object, e As EventArgs)
               End Sub
               Private Sub BtnOpen_Click(sender As Object, e As EventArgs)
                               Dim dialog As New OpenFileDialog()
                               dialog.Filter = "PDF document (*.pdf)|*.pdf"
                               Dim result As DialogResult = dialog.ShowDialog()
                               If result = DialogResult.OK Then
                                              Try
                                                             Dim pdfFile As String = dialog.FileName
                                              Me.pdfDocumentViewer1.LoadFromFile(pdfFile)
                                              Catch exe As Exception
                                                             MessageBox.Show(exe.Message, "Spire.PdfViewer Demo", MessageBoxButtons.OK, MessageBoxIcon.[Error])
                                              End Try
                               End If
               End Sub

3.   Save the PDF file. This step enables you not only to save the PDF file but also to view the PDF Document page by selecting the page number in ComboBox dropdown list. 

C# Code:
        private void BtnSave_Click(object sender, EventArgs e)
        {
            if (this.pdfDocumentViewer1.PageCount > 0)
            {
                SaveFileDialog dialog = new SaveFileDialog();
                dialog.Filter = "PDF document (*.pdf)|*.pdf";
                DialogResult result = dialog.ShowDialog();
                string fileName = dialog.FileName;
                if (result == DialogResult.OK)
                {
                    pdfDocumentViewer1.SaveToFile(fileName);
                    MessageBox.Show("You have saved this PdfDocuemnt as:\n" + fileName, "Spire.PdfViewer Demo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
        private void BtnSaveStream_Click(object sender, EventArgs e)
        {
            if (this.pdfDocumentViewer1.PageCount > 0)
            {
                SaveFileDialog dialog = new SaveFileDialog();
                dialog.Filter = "PDF document (*.pdf)|*.pdf";
                DialogResult result = dialog.ShowDialog();
                string fileName = dialog.FileName;
                if (result == DialogResult.OK)
                {
                    MemoryStream stream = new MemoryStream();
                    pdfDocumentViewer1.SaveToFile(stream);
                    byte[] fileBytes = stream.ToArray();
                    FileStream fileStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite);
                    fileStream.Write(fileBytes, 0, fileBytes.Length);
                    fileStream.Flush();
                    fileStream.Close();
                    stream.Close();
                    MessageBox.Show("You have first saved this PDF docuemnt as memory stream,\nthen write the memory stream in a file :\n" + fileName, "Spire.PdfViewer Demo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
        private void pdfDocumentViewer1_PdfLoaded(object sender, EventArgs args)
        {
            this.comBoxPages.Items.Clear();
            int totalPage = this.pdfDocumentViewer1.PageCount;
            for (int i = 1; i <= totalPage; i++)
            {
                this.comBoxPages.Items.Add(i.ToString());
            }
            this.comBoxPages.SelectedIndex = 0;
        }
        private void pdfDocumentViewer1_PageNumberChanged(object sender, EventArgs args)
        {
            if (this.comBoxPages.Items.Count <= 0)
                return;
            if (this.pdfDocumentViewer1.CurrentPageNumber != this.comBoxPages.SelectedIndex + 1)
            {
                this.comBoxPages.SelectedIndex = this.pdfDocumentViewer1.CurrentPageNumber - 1;
            }
        }
        private void comBoxPages_SelectedIndexChanged(object sender, EventArgs e)
        {
            int soucePage = this.pdfDocumentViewer1.CurrentPageNumber;
            int targetPage = this.comBoxPages.SelectedIndex + 1;
            if (soucePage != targetPage)
            {
                this.pdfDocumentViewer1.GoToPage(targetPage);
            }
        }

VB.NET Code:

               Private Sub BtnSave_Click(sender As Object, e As EventArgs)
                               If Me.pdfDocumentViewer1.PageCount > 0 Then
                                              Dim dialog As New SaveFileDialog()
                                              dialog.Filter = "PDF document (*.pdf)|*.pdf"
                                              Dim result As DialogResult = dialog.ShowDialog()
                                              Dim fileName As String = dialog.FileName
                                              If result = DialogResult.OK Then
                                                             pdfDocumentViewer1.SaveToFile(fileName)
                                                            MessageBox.Show("You have saved this PdfDocuemnt as:" & vbLf & fileName, "Spire.PdfViewer Demo", MessageBoxButtons.OK,MessageBoxIcon.Information)
                                              End If
                               End If
               End Sub
               Private Sub BtnSaveStream_Click(sender As Object, e As EventArgs)
                               If Me.pdfDocumentViewer1.PageCount > 0 Then
                                              Dim dialog As New SaveFileDialog()
                                              dialog.Filter = "PDF document (*.pdf)|*.pdf"
                                              Dim result As DialogResult = dialog.ShowDialog()
                                              Dim fileName As String = dialog.FileName
                                              If result = DialogResult.OK Then
                                                             Dim stream As New MemoryStream()
                                                             pdfDocumentViewer1.SaveToFile(stream)
                                                             Dim fileBytes As Byte() = stream.ToArray()
                                                             Dim fileStream As New FileStream(fileName, FileMode.Create, FileAccess.ReadWrite)
                                                             fileStream.Write(fileBytes, 0, fileBytes.Length)
                                                             fileStream.Flush()
                                                             fileStream.Close()
                                                             stream.Close()
                                                             MessageBox.Show("You have first saved this PDF docuemnt as memory stream," & vbLf & "then write the memory stream in a file :" & vbLf & fileName, "Spire.PdfViewer Demo", MessageBoxButtons.OK, MessageBoxIcon.Information)
                                              End If
                               End If
               End Sub
               Private Sub pdfDocumentViewer1_PdfLoaded(sender As Object, args As EventArgs)
                               Me.comBoxPages.Items.Clear()
                               Dim totalPage As Integer = Me.pdfDocumentViewer1.PageCount
                               For i As Integer = 1 To totalPage
                                              Me.comBoxPages.Items.Add(i.ToString())
                               Next
                               Me.comBoxPages.SelectedIndex = 0
               End Sub
               Private Sub pdfDocumentViewer1_PageNumberChanged(sender As Object, args As EventArgs)
                               If Me.comBoxPages.Items.Count <= 0 Then
                                              Return
                               End If
                               If Me.pdfDocumentViewer1.CurrentPageNumber <> Me.comBoxPages.SelectedIndex + 1 Then
                                              Me.comBoxPages.SelectedIndex = Me.pdfDocumentViewer1.CurrentPageNumber - 1
                               End If
               End Sub
               Private Sub comBoxPages_SelectedIndexChanged(sender As Object, e As EventArgs)
                               Dim soucePage As Integer = Me.pdfDocumentViewer1.CurrentPageNumber
                               Dim targetPage As Integer = Me.comBoxPages.SelectedIndex + 1
                               If soucePage <> targetPage Then
                                              Me.pdfDocumentViewer1.GoToPage(targetPage)
                               End If
               End Sub

4.     Check the Events of your buttons, comBoBox and pdfDocumentViewer.
Tools                                    Events                                  As
Open                              Click                               BtnOpen_Click
Save                              Click                               BtnSave_ClickSave Sream  
SaveSream                         Click                               BtnSaveStream_ClickcomBoxPages 
comBoxPages                   SelectedIndexChanged      comBoxPages_SelectedIndexChanged 
pdfDocumentViewer1         PageNumberChanged         pdfDocumentViewer1_PageNumberChanged
pdfDocumentViewer1         PdfLoaded                       pdfDocumentViewer1_PdfLoaded                    

Step4. Debug the project.

After debugging, you can preview the effect.
                           


Found interesting? Add this to:



Comments or Responses


Login to post response.

Comments / Responses
Select text & click toolbar to format. Formatting appears in viewmode only. HTML Tags are not allowed.
Bold Italic Underline Paragraph Title Code  Link 
 Wait ... Processing ..... please wait.