Scenario:
1- Download a PDf file.2- Store it on a specific Directory. In my case d:\Avinash\filename.pdf
3- Read the Downloaded file using in C#
4- Show the Contents of each page on the screen.
Introduction:
Download a Pdf file using selenium WebDriver. I have set the preferences in firefox browser to tell the browser which kind of file is going to handle and what action should take while downloading that file.Below example is for to dowmload the pdf file from google.com. But in my firefox their is an already integration of IDM(Internet Download Manager) with Mozilla. so whenever I will download that file the IDM's file download dialog is open.
See below screenshot.
So In my case to handle the IDM's file Download Dialog I have Used thirty party tool as "AutoIt V3" to handle windows Button or Control on Internet Download manager Dialog.
Prerequisite:
1-Visual Studio any version
2- Install / Add "ITextSharp.dll" through the NuGet package in current project / Solution.
3- AutoIt V3 Scripting tool.
4- AutoIt Window Info.
5- NUnit Testing framework.
Procedure:
1-Open visual Studio.
2- Select File -> New project -> Select Test -> Select Unit Test.
3- Give project Name as "DownloadPDFandreadPDF".
4- Install "itextSharp" from Nuget. see below ScreenShot.
Select Tools menu-> select Library Package manager->Manage NuGet packages for Solution.
5- Remove the Existing refernce of Unit Testing and add the reference of Nunit.
using Microsoft.VisualStudio.TestTools.UnitTesting; - Remove It. &
Add using using NUnit.Framework;
6 Add the respective references for selenium.
Code :
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
using NUnit.Framework;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
using System.IO;
namespace DownloadPDFandreadPDF
{
[TestFixture]
public class DownloadPDFAndRead
{
IWebDriver driver = null;
IWebElement element = null;
FirefoxProfile FProfile = null;
String DownloadfilePath = "d:\\Avinash";
[SetUp]
public void BeforeTest()
{
FirefoxProfile profileSetUp = FirefoxProfilesetup(DownloadfilePath);
driver = new FirefoxDriver(profileSetUp);
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
driver.Navigate().GoToUrl("http://www.google.com");
}
[Test]
public void TestDownloadPDFAndRead()
{
driver.FindElement(By.Id("lst-ib")).SendKeys("selenium webdriver practical guide pdf");
driver.FindElement(By.XPath("//button[@value='Search']")).Click();
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.ElementIsVisible(By.PartialLinkText("Selenium WebDriver Practical
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
using NUnit.Framework;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
using System.IO;
namespace DownloadPDFandreadPDF
{
[TestFixture]
public class DownloadPDFAndRead
{
IWebDriver driver = null;
IWebElement element = null;
FirefoxProfile FProfile = null;
String DownloadfilePath = "d:\\Avinash";
[SetUp]
public void BeforeTest()
{
FirefoxProfile profileSetUp = FirefoxProfilesetup(DownloadfilePath);
driver = new FirefoxDriver(profileSetUp);
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
driver.Navigate().GoToUrl("http://www.google.com");
}
[Test]
public void TestDownloadPDFAndRead()
{
driver.FindElement(By.Id("lst-ib")).SendKeys("selenium webdriver practical guide pdf");
driver.FindElement(By.XPath("//button[@value='Search']")).Click();
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.ElementIsVisible(By.PartialLinkText("Selenium WebDriver Practical
Guide")));
driver.FindElement(By.PartialLinkText("Selenium WebDriver Practical Guide")).Click();
System.Threading.Thread.Sleep(5000);
//In my case I have installed Internet Download Manager & it is configured with Firefox
//so to handle internet download manager dialog I have used Autoit tool to handle it.
System.Threading.Thread.Sleep(5000);
System.Diagnostics.Process.Start("G:\\Autoit\\DownloadPDFFile.exe");
Console.WriteLine("file Download Completed.....!");
ReadPDF("d:\\Avinash\\9781782168850_Sample.pdf");
}
[TearDown]
public void AfterTest()
{
element = null;
driver.Close();
}
/// <summary>
/// Set the preference in firefox. which kind of file(extension)you are downloading & how to handle
driver.FindElement(By.PartialLinkText("Selenium WebDriver Practical Guide")).Click();
System.Threading.Thread.Sleep(5000);
//In my case I have installed Internet Download Manager & it is configured with Firefox
//so to handle internet download manager dialog I have used Autoit tool to handle it.
System.Threading.Thread.Sleep(5000);
System.Diagnostics.Process.Start("G:\\Autoit\\DownloadPDFFile.exe");
Console.WriteLine("file Download Completed.....!");
ReadPDF("d:\\Avinash\\9781782168850_Sample.pdf");
}
[TearDown]
public void AfterTest()
{
element = null;
driver.Close();
}
/// <summary>
/// Set the preference in firefox. which kind of file(extension)you are downloading & how to handle
the download dialog.
/// </summary>
/// <param name="DownloadfilePath">Specify the path where to keep the downloaded PDF
/// </summary>
/// <param name="DownloadfilePath">Specify the path where to keep the downloaded PDF
file.</param>
/// <returns></returns>
public FirefoxProfile FirefoxProfilesetup(String DownloadfilePath)
{
FProfile = new FirefoxProfile();
FProfile.SetPreference("browser.download.folderList", 2);
//profile.SetPreference("browser.download.manager.showWhenStarting", true);//added
FProfile.SetPreference("browser.download.dir", DownloadfilePath);
FProfile.SetPreference("browser.helperApps.neverAsk.openFile",
"text/csv,application/x-msexcel,application/excel,application/x-excel,application
/// <returns></returns>
public FirefoxProfile FirefoxProfilesetup(String DownloadfilePath)
{
FProfile = new FirefoxProfile();
FProfile.SetPreference("browser.download.folderList", 2);
//profile.SetPreference("browser.download.manager.showWhenStarting", true);//added
FProfile.SetPreference("browser.download.dir", DownloadfilePath);
FProfile.SetPreference("browser.helperApps.neverAsk.openFile",
"text/csv,application/x-msexcel,application/excel,application/x-excel,application
/vnd.ms-excel,image/png,image/jpeg,text/html,text/plain,application/msword,application/xml");
FProfile.SetPreference("browser.helperApps.neverAsk.saveToDisk",
"text/csv,application/x-msexcel,application/excel,application/x-excel,application
FProfile.SetPreference("browser.helperApps.neverAsk.saveToDisk",
"text/csv,application/x-msexcel,application/excel,application/x-excel,application
/vnd.ms-excel,image/png,image/jpeg,text/html,text/plain,application/msword,application/xml");
FProfile.SetPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf");
FProfile.SetPreference("browser.helperApps.alwaysAsk.force", false);
FProfile.SetPreference("browser.download.manager.alertOnEXEOpen", false);
FProfile.SetPreference("browser.download.manager.focusWhenStarting", false);
FProfile.SetPreference("browser.download.manager.useWindow", false);
FProfile.SetPreference("browser.download.manager.showAlertOnComplete", false);
FProfile.SetPreference("browser.download.manager.closeWhenDone", false);
FProfile.SetPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf");
FProfile.SetPreference("browser.helperApps.alwaysAsk.force", false);
FProfile.SetPreference("browser.download.manager.alertOnEXEOpen", false);
FProfile.SetPreference("browser.download.manager.focusWhenStarting", false);
FProfile.SetPreference("browser.download.manager.useWindow", false);
FProfile.SetPreference("browser.download.manager.showAlertOnComplete", false);
FProfile.SetPreference("browser.download.manager.closeWhenDone", false);
FProfile.SetPreference("browser.download.manager.showAlertOnComplete", true); //added alert
should show after completion
return FProfile;
}
/// <summary>
/// Read the contents of Downloaded .pdf file and prints on the screen
/// </summary>
/// <param name="PDFFilePath">Path to the downloaded file</param>
public void ReadPDF(String PDFFilePath)
{
PdfReader reader = new PdfReader(PDFFilePath);
String PDFContents = PdfTextExtractor.GetTextFromPage(reader, 1);
Console.WriteLine("File length:"+ reader.FileLength);
Console.WriteLine("No. Of pages"+reader.NumberOfPages);
System.Text.StringBuilder sb = new System.Text.StringBuilder();
ITextExtractionStrategy its = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();
for (int i = 1; i < reader.NumberOfPages; i++)
{
sb.Clear();
sb = sb.Append(PdfTextExtractor.GetTextFromPage(reader, i, its));
Console.WriteLine("Contents of Page{0}:{1}",i, sb);
}
try
{
reader.Close();
}
catch
{
Console.WriteLine("Exception Occured while reading PDF File....!");
}
}
}
}
return FProfile;
}
/// <summary>
/// Read the contents of Downloaded .pdf file and prints on the screen
/// </summary>
/// <param name="PDFFilePath">Path to the downloaded file</param>
public void ReadPDF(String PDFFilePath)
{
PdfReader reader = new PdfReader(PDFFilePath);
String PDFContents = PdfTextExtractor.GetTextFromPage(reader, 1);
Console.WriteLine("File length:"+ reader.FileLength);
Console.WriteLine("No. Of pages"+reader.NumberOfPages);
System.Text.StringBuilder sb = new System.Text.StringBuilder();
ITextExtractionStrategy its = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();
for (int i = 1; i < reader.NumberOfPages; i++)
{
sb.Clear();
sb = sb.Append(PdfTextExtractor.GetTextFromPage(reader, i, its));
Console.WriteLine("Contents of Page{0}:{1}",i, sb);
}
try
{
reader.Close();
}
catch
{
Console.WriteLine("Exception Occured while reading PDF File....!");
}
}
}
}
AutoIt Code:
1- Open SciTE editor.
2- Open the AutoIt Window Info
3- Drag and Drop the Finder tool on control which we required to handle.
like downlad path and start button on IDM download dialog.
4- We will get the information as title , text, ControlId etc. see the below screen shot.
5- Write / paste the below code in SCiTE editor and save as .au3 extension.
AutoIt Code:
ControlFocus("Download File Info","","Edit4");
ControlSetText("Download File Info","","Edit4","d:\Avinash\Avinash.pdf");
ControlClick("Download File Info","","Button1");
ControlSetText("Download File Info","","Edit4","d:\Avinash\Avinash.pdf");
ControlClick("Download File Info","","Button1");
Excecute:
1- Compile the whole project in visual studio.
2- Open the Nunit Application from start menu.
3- Select file -> Open project -> go to the path where current project .dll is located.
4- Select the .DLL having same name as your current Project in this case "DownloadPDFandreadPDF.dll"
5- Click on run button for execution.
Note: using thread.Sleep() will cause delay in execution. Standard says don't use excessive. User WebdriverWait, defaultWait etc....
I Want To Open Gmail Inbox [Particular Message] .But Am Unable To Open Using C#. .So Please Help Me
ReplyDeleteSelenium Automation Blogs By Avinash Pande: File Using Selenium Webdriver C >>>>> Download Now
Delete>>>>> Download Full
Selenium Automation Blogs By Avinash Pande: File Using Selenium Webdriver C >>>>> Download LINK
>>>>> Download Now
Selenium Automation Blogs By Avinash Pande: File Using Selenium Webdriver C >>>>> Download Full
>>>>> Download LINK Co
This comment has been removed by the author.
ReplyDeleteHi Avinash, Nice logic. But can you suggest a solution where I use ChromeDriver with C# & I want to open a page which has PDF embedded in it & instead of it getting viewed in chromedriver, it should download to default directory.
ReplyDeleteSelenium Automation Blogs By Avinash Pande: File Using Selenium Webdriver C >>>>> Download Now
ReplyDelete>>>>> Download Full
Selenium Automation Blogs By Avinash Pande: File Using Selenium Webdriver C >>>>> Download LINK
>>>>> Download Now
Selenium Automation Blogs By Avinash Pande: File Using Selenium Webdriver C >>>>> Download Full
>>>>> Download LINK 8Q