iTextSharp reader javascript error RSS - c#

I found yesterday on google iTextSharp for pdf filling data.
but when i trying to read pdf ,i am not getting acrofields from pdf .
Here is code
private void ListFieldNames()
{
string pdfTemplate = #"E:\Vikas\Projects\PdfWriter\PdfWriter\nbc-app.pdf";
// create a new PDF reader based on the PDF template document
PdfReader pdfReader = new PdfReader(pdfTemplate);
AcroFields formfields = pdfReader.AcroFields;
// create and populate a string builder with each of the
// field names available in the subject PDF
foreach (KeyValuePair<string, AcroFields.Item> de in formfields.Fields)
{
sb.Append(de.Key.ToString() + Environment.NewLine);
}
// Write the string builder's content to the form's textbox
txtbx.TextMode = TextBoxMode.MultiLine;
txtbx.Width = 500;
txtbx.Rows = 40;
txtbx.Text = sb.ToString();
//txtbx.SelectionStart = 0;
}
Than i was doing debugging i saw reader.javascript throwing error (error is below )
if (typeof(this.ADBE) == "undefined")
this.ADBE = new Object();
ADBE.LANGUAGE = "ENU";
ADBE.Viewer_string_Title = "Adobe Acrobat";
ADBE.Viewer_string_Update_Desc = "Adobe Interactive Forms Update";
ADBE.Viewer_string_Update_Reader_Desc = "Adobe Reader 7.0.5";
ADBE.Reader_string_Need_New_Version_Msg = "This PDF file requires a newer version of Adobe Reader. Press OK to download the latest version or see your system administrator.";
ADBE.Viewer_Form_string_Reader_601 = "This PDF form requires a newer version of Adobe Reader. Although the form may appear to work properly, some elements may function improperly or may not appear at all. Press OK to initiate an online update or see your system administrator.";
ADBE.Viewer_Form_string_Reader_Older = "This PDF form requires a newer version of Adobe Reader. Although the form may appear to work properly, some elements may function improperly or may not appear at all. Press OK for online download information or see your system administrator.";
ADBE.Viewer_Form_string_Viewer_601 = "This PDF form requires a newer version of Adobe Acrobat. Although the form may appear to work properly, some elements may function improperly or may not appear at all. Press OK to initiate an online update or see your system administrator.";
ADBE.Viewer_Form_string_Viewer_60 = "This PDF form requires a newer version of Adobe Acrobat. Although the form may appear to work properly, some elements may function improperly or may not appear at all. For more information please copy the following URL (CTRL+C on Win, Command-C on Mac) and paste into your browser or see your system administrator.";
ADBE.Viewer_Form_string_Viewer_Older = "This PDF requires a newer version of Acrobat. Copy this URL and paste into your browser or see your sys admin.";
ADBE.Viewer_Form_string_Reader_5x = "This PDF form requires a newer version of Adobe Reader. Without a newer version, the form may be displayed, but it might not work properly. Some form elements might not be visible at all. If an internet connection is available, clicking OK will open your browser to a web page where you can obtain the latest version.";
ADBE.Viewer_Form_string_Reader_6_7x = "This PDF form requires a newer version of Adobe Reader. Without a newer version, the form may be displayed, but it might not work properly. Some form elements might not be visible at all. If an internet connection is available, clicking OK will download and install the latest version.";
ADBE.Viewer_Form_string_Viewer = "This PDF form requires a newer version of Adobe Acrobat. Without a newer version, the form may be displayed, but it might not work properly. Some form elements might not be visible at all. If an internet connection is available, clicking OK will download and install the latest version.";
if (typeof(ADBE.Reader_Value_Asked) == "undefined")
ADBE.Reader_Value_Asked = false;
if (typeof(ADBE.Viewer_Value_Asked) == "undefined")
ADBE.Viewer_Value_Asked = false;
if (typeof(ADBE.Reader_Need_Version) == "undefined" || ADBE.Reader_Need_Version < 8.1)
{
ADBE.Reader_Need_Version = 8.1;
ADBE.Reader_Value_New_Version_URL = "http://cgi.adobe.com/special/acrobat/update";
ADBE.SYSINFO = "?p=" + app.platform + "&v=" + app.viewerVersion + "&l=" + app.language + "&c=" + app.viewerType + "&r=" + ADBE.Reader_Need_Version;
}
if (typeof(ADBE.Viewer_Need_Version) == "undefined" || ADBE.Viewer_Need_Version < 8.1)
{
ADBE.Viewer_Need_Version = 8.1;
ADBE.Viewer_Value_New_Version_URL = "http://cgi.adobe.com/special/acrobat/update";
ADBE.SYSINFO = "?p=" + app.platform + "&v=" + app.viewerVersion + "&l=" + app.language + "&c=" + app.viewerType + "&r=" + ADBE.Viewer_Need_Version;
}
if (typeof(xfa_installed) == "undefined" || typeof(xfa_version) == "undefined" || xfa_version < 2.6)
{
if (app.viewerType == "Reader")
{
if (ADBE.Reader_Value_Asked != true)
{
if (app.viewerVersion < 8.0)
{
if (app.alert(ADBE.Reader_string_Need_New_Version_Msg, 1, 1) == 1)
this.getURL(ADBE.Reader_Value_New_Version_URL + ADBE.SYSINFO, false);
ADBE.Reader_Value_Asked = true;
}
else if (app.alert(ADBE.Viewer_Form_string_Viewer, 1, 1) == 1)
app.findComponent({cType:"Plugin", cName:"XFA", cVer:"2.6"});
}
}
else
{
if (ADBE.Viewer_Value_Asked != true)
{
if (app.viewerVersion < 7.0)
app.response({cQuestion: ADBE.Viewer_Form_string_Viewer_Older, cDefault: ADBE.Viewer_Value_New_Version_URL + ADBE.SYSINFO, cTitle: ADBE.Viewer_string_Title});
else if (app.viewerVersion < 8.0)
{
if (app.alert(ADBE.Viewer_Form_string_Viewer, 1, 1) == 1)
app.launchURL(ADBE.Viewer_Value_New_Version_URL + ADBE.SYSINFO, true);
}
else if (app.alert(ADBE.Viewer_Form_string_Viewer, 1, 1) == 1)
app.findComponent({cType:"Plugin", cName:"XFA", cVer:"2.6"});
ADBE.Viewer_Value_Asked = true;
}
}
}
how should i fixed this problem ?

Related

selenium AutoIt Keyboard Types Incorrectly

I'm Using AutoIt While Uploading Selenium Files.
But While Uploading, It Enters the File Path Wrong.
autoIt = new AutoItX3();
autoIt.WinActivate("Farklı Kaydet");
Thread.Sleep(1000);
autoIt.Send(AppDomain.CurrentDomain.BaseDirectory + #"video" + #"\" + textBox7.Text + "", 787000);
autoIt.Send("{ENTER}");
How can I make the keyboard type slower and smoother?
787000
I Added But It Still Runs Fast and looking for wrong file path.
How do I solve this with c#
Tiktoka. I'm Trying to Upload Video
First, I would not use autoIt for a file upload unless absolutely necessary. Hopefully you can just do it through the input element on the page. See here if you are not sure how to do it. How to handle Windows file upload in .Net core using Selenium?
As for your question, type the characters individually. You can also create an additional try/catch so that if the typed value does not equal the displayed value, you can delete it and do it again.
public static void TypeCharIndividually(IWebElement element, string expectedValue)
{
if (expectedValue == null)
{
return;
}
if (expectedValue == "n/a") { expectedValue = ""; }
Driver.WaitForElementDisplayed(element);
Driver.WaitForElementEnabled(element);
element.Click();
element.Clear();
foreach (char c in expectedValue)
{
element.SendKeys(c.ToString());
Thread.Sleep(500);
Driver.WaitForSpinnerNoLongerDisplayed();
}
element.SendKeys(Keys.Tab);
string receivedValue = element.GetAttribute("value");
if (receivedValue != expectedValue)
{
throw new Exception("Typed element not as expected");
}

CEFSharp app displays blank screen and then responds on it's own after a minute

I've been working on a app which uses CEFSharp (version 83.4.20) to load my companies VOIP platform (engage.ringcentral.com). The source is up on Github https://github.com/dylanlangston/EngageRC
The app has been working for about a month now and after putting it into production I've received reports of an odd issue. People are seeing a blank screen and unable to interact with the webpage (
Example of issue ). After a few minutes the issue seems to resolve itself and their able to interact with the webpage again. I haven't been able to reproduce the issue myself.
I thought this might be a rendering issue. So far I've tried to adjust the following in my app:
Remove the lines below.
settings.CefCommandLineArgs.Add("disable-gpu");
settings.CefCommandLineArgs.Add("disable-gpu-shader-disk-cache", "1");
Replace them with.
settings.CefCommandLineArgs.Add("disable-gpu-compositing");
Unfortunately this hasn't resolved the issues and I'm unsure what I'm missing.
The relevant code for CEF Initialization is located in https://github.com/dylanlangston/EngageRC/blob/master/Windows/MainWindow.Designer.cs under the InitializeChromium method. See Below
//
// Chrome
//
private CefSharp.WinForms.ChromiumWebBrowser chromeBrowser;
public ChromiumWebBrowser InitializeChromium(string URL, string Name)
{
// Check if already Initialized
if (Cef.IsInitialized == false)
{
CefSettings settings = new CefSettings();
// Enable Logging if debugging or console window
if (!this.debug || !this.console)
{
settings.LogSeverity = LogSeverity.Disable;
}
else
{
settings.LogSeverity = LogSeverity.Verbose;
}
// Enable Microphone settings
settings.CefCommandLineArgs.Add("enable-media-stream", "1");
// Set Custom Browser Paths
settings.CefCommandLineArgs.Add("disable-gpu-shader-disk-cache", "1");
// Disable GPU to fix rendering issues on some machines.
settings.CefCommandLineArgs.Add("disable-gpu");
// Disable CORS protection (cross site scripting) which the engage.ringcentral.com site doesn't seem to like/respect, disabled as the website doesn't seem to improve with this turned on.
//settings.CefCommandLineArgs.Add("disable-web-security");
// Enable session Cookie persistence, disabled as it's unneeded.
//settings.PersistSessionCookies = true;
// Custom Browser paths
settings.BrowserSubprocessPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"Resources\CEFSharp\CefSharp.BrowserSubprocess.exe");
settings.LocalesDirPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"Resources\CEFSharp\locales\");
settings.ResourcesDirPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"Resources\CEFSharp\");
// Check if Resources folder is writable. If it isn't then write to application data.
DirectoryInfo di = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"Resources\CEFSharp\"));
if ((di.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
settings.RootCachePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), #"EngageRC\CEFSharp\cache");
settings.CachePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), #"EngageRC\CEFSharp\cache");
settings.LogFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), #"EngageRC\CEFSharp\debug.log");
}
else
{
settings.RootCachePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"Resources\CEFSharp\cache");
settings.CachePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"Resources\CEFSharp\cache");
settings.LogFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"Resources\CEFSharp\debug.log");
}
// Initialize cef with the provided settings or add new tab
Cef.Initialize(settings, performDependencyCheck: true, browserProcessHandler: null);
}
// Create a browser component
chromeBrowser = new ChromiumWebBrowser(URL);
// Set Name
chromeBrowser.Name = Name;
// Adjust size and scaling
this.chromeBrowser.Dock = DockStyle.Fill;
this.chromeBrowser.Width = this.Width;
this.chromeBrowser.Height = this.Height;
// Add control
this.Controls.Add(chromeBrowser);
// Bring to front
this.chromeBrowser.BringToFront();
// Set label to Goodbye.
this.label1.Text = "Goodbye";
// Return control
return chromeBrowser;
}
I wasn't able to find any previous questions with my Google foo so it seems this isn't something other's are seeing their applications. I'm still learning the ropes when it comes to C# so it's 100% possible this is my own fault and something I'm doing wrong.
I was able to get verbose logging from a machine that experienced the issue. I'm mostly seeing the following error. Full logs at https://gist.github.com/dylanlangston/194e389ead437e6c6fe08b2d4746bf43
[0729/083616.491:ERROR:paint_controller.cc(646)] PaintController::FinishCycle() completed
Any ideas or recommendations to help troubleshoot this is appreciated!
Updated: Based on #amaitland's helpful comments it seems this behavior may be caused by using Thread.Sleep on a thread on I'm not supposed to.
After reviewing my code it looks like I have this in two locations.
First I call thread.sleep to wait until the browsers zoom level matches the value I've saved to the windows isolatedstorage. This shouldn't be running except when the application first starts. I don't think this is the problem but I am posting it here anyways to be safe. (https://github.com/dylanlangston/EngageRC/blob/master/CEFSharpHandlers.cs)
public void OnLoadingStateChanged(object sender, LoadingStateChangedEventArgs args)
{
ChromiumWebBrowser chrome = (ChromiumWebBrowser)sender;
if (!args.IsLoading) // Loading finished.
{
// If first load set zoom level to previous level
if (firstLoad < 3)
{
try
{
double zoom = double.Parse(ConfigReader.ReadIsolatedStorage("z"), System.Globalization.CultureInfo.InvariantCulture);
while (args.Browser.GetZoomLevelAsync().Result != zoom) { chrome.SetZoomLevel(zoom); Thread.Sleep(50); }
}
catch { }
firstLoad++;
}
// These JS and CSS modifications built into EngageRC
string hotfixJS = "";
string hotfixCSS = "/* Fix for dropdowns */ ul.dropdown-menu[style=\\\"opacity: 1;\\\"] {display: block !important; } /* End fix for dropdowns */";
// Inject custom javascript and css code on page load
chrome.ExecuteScriptAsync(hotfixJS);
chrome.ExecuteScriptAsync("var engageRCSS = document.getElementById('EngageRCSS'); if (!engageRCSS) { var node = document.createElement('style'); node.setAttribute('id', 'EngageRCSS'); node.innerHTML = \"" + hotfixCSS +"\"; document.body.appendChild(node); }");
if (File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"Resources\Custom.js"))) { chrome.ExecuteScriptAsync(System.IO.File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"Resources\Custom.js"))); }
if (File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"Resources\Custom.css"))) { chrome.ExecuteScriptAsync("var customCSS = document.getElementById('customcss'); if (!customCSS) { var node = document.createElement('style'); node.setAttribute('id', 'customcss'); node.innerHTML = \"" + System.IO.File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"Resources\Custom.css")).Replace("\n", String.Empty).Replace("\r", String.Empty).Replace("\t", String.Empty).Replace("\"", "\\\"") + "\"; document.body.appendChild(node); }"); }
}
}
I also have it when displaying a notification. This is most likely my problem as this is running in the main application thread... (https://github.com/dylanlangston/EngageRC/blob/master/NotificationSupport.cs)
public void displayNotification(string Title = "EngageRC", string Message = "")
{
// Display notification for 5 seconds
Notify notification = MainWindow.notification;
try
{
if (!IsActive(hWnd)) // Check if application is already active.
{
string config = ConfigReader.GetConfigValue("NotificationsDisabled").ToLower();
if (!(config == "true" || config == "1"))
{
notification.NewNotification(Title, Message, 5000);
}
config = ConfigReader.GetConfigValue("GetFocusOnCallDisabled").ToLower();
if (!(config == "true" || config == "1") && (Message == "You have incoming call"))
{
// Minimize window
ShowWindow(hWnd, 0x02);
// Restore window to previous state.
ShowWindow(hWnd, 0x09);
}
config = ConfigReader.GetConfigValue("GetFocusOnPendingDispositionDisabled").ToLower();
if (!(config == "true" || config == "1") && (Message == "You have a disposition pending"))
{
// Minimize window
ShowWindow(hWnd, 0x02);
// Restore window to previous state.
ShowWindow(hWnd, 0x09);
}
}
}
catch { notification.SetIconVisible(false); }
finally
{
Thread.Sleep(4999);
notification.SetIconVisible(false);
}
}
Based on what I've heard I should make the Notification Form run on a different thread from the main application then? Or am I way off base?
Update:
I was able to move the notification into it's own thread. I'm closing this issue and will have the user's test to see if the blank screen persists.
Thanks for the help again!!
#amaitland's comments were helpful in narrowing this issue down.

"How to make a windows form communicate with Microsoft Office?"

My programs works perfectly with using hotkeys in place to alter text in Microsoft Word, Powerpoint, Excel, and Outlook.
The only problem I have is that the program will not execute unless I either click on it with the mouse or use Alt and Tab to toggle between my program and Microsoft Office programs.
I wish to not use the mouse or use Alt and Tab. I have a keyboard hook script in place to copy the hotkeys, but it will only work if Windows sees my program on top of everything and is active.
I have my program on top of everything, but when going to Microsoft Word (for example), my program is no longer active and Microsoft Word is now active. I would have to go to my program to make it active by clicking on it with my mouse or using Alt and Tab, perform the hotkey and then go back to Microsoft Word with using my mouse to click on it or using Alt and Tab to make it active to use the hotkey that was pressed.
With this, how would I go about and make my program a shared plugin for Microsoft Office, to where when it is running, Microsoft Office will recognize my program?
First of all, you can automate Outlook form other applications. Due to the fact that Outlook is a singleton only one application instance can be run at the same time on the system. So, you may get a running instance from the ROT:
//Get reference to Outlook.Application from the ROT.
oApp = (Outlook.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Outlook.Application");
If there is no Outlook running on the system you may simply create a new one. See C# app automates Outlook (CSAutomateOutlook) for more information.
Here is my code for you to view so you have an idea what I am doing.
Sorry, I tried to put it as a comment, but it was too long.
//MICROSOFT WORD INTEGRATION
try
{
app = (Microsoft.Office.Interop.Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
app.ActiveWindow.Selection.Font.Color = (Microsoft.Office.Interop.Word.WdColor)(changeColor.R + 0x100 * changeColor.G + 0x10000 * changeColor.B);
}
catch (System.Exception excp)
{
}
//MICROSOFT EXCEL INTEGRATION
try
{
xlApp = (Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
xlBook = xlApp.ActiveWorkbook;
xlSheet = xlBook.ActiveSheet;
Microsoft.Office.Interop.Excel.Range rngSelection = xlApp.Selection as Microsoft.Office.Interop.Excel.Range;
for (var r = 1; r <= rngSelection.Rows.Count; r++)
{
for (var c = 1; c <= rngSelection.Columns.Count; c++)
{
rngSelection[r, c].Font.Color = copyProgramText.SelectionColor;
}
}
}
catch (System.Exception excp)
{
}
//MICROSOFT POWERPOINT INTEGRATION
try
{
pwptApp = (Microsoft.Office.Interop.PowerPoint.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("PowerPoint.Application");
pwptApp.ActiveWindow.Selection.TextRange.Font.Color.RGB = System.Drawing.ColorTranslator.ToOle(changeColor);
if (pwptApp.ActiveWindow.Selection.TextRange.Text.Trim() == "") pwptApp.ActiveWindow.Selection.TextRange.Text = " ";
}
catch (System.Exception excp)
{
}
//MICROSOFT OUTLOOK INTEGRATION
try
{
Microsoft.Office.Interop.Outlook.Application otlkApp = (Microsoft.Office.Interop.Outlook.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Outlook.Application");
Microsoft.Office.Interop.Outlook.Explorer otlkExp = otlkApp.ActiveExplorer();
Microsoft.Office.Interop.Outlook.Selection otlkSel = otlkExp.Selection;
Microsoft.Office.Interop.Outlook.MailItem otlkMsg = otlkApp.ActiveInspector().CurrentItem as Microsoft.Office.Interop.Outlook.MailItem;
Microsoft.Office.Interop.Outlook.Inspector insp = otlkMsg.GetInspector;
Microsoft.Office.Interop.Word.Document otlkDoc = (Microsoft.Office.Interop.Word.Document)insp.WordEditor;
string sepSel = otlkDoc.Application.Selection.Text;
byte rColor = changeColor.R;
byte gColor = changeColor.G;
byte bColor = changeColor.B;
if (sepSel.Trim() == "\r") return;
char cReturn = (char)13;
if (sepSel == cReturn.ToString()) return;
if (sepSel != "")
{
otlkMsg.HTMLBody = otlkMsg.HTMLBody.Replace(sepSel, "<font style = 'color: rgb(" + rColor.ToString() + ", " + gColor.ToString() + ", " + bColor.ToString() + ")'>" + sepSel + " </font>");
}
else
{
return;
}
prevOutlookContents = otlkMsg.HTMLBody;
}
catch (System.Exception excp)
{
}

open window explorer folder from my results c#

iv made a web forum, as i have lots of folders on my local drive i can now search for any folders i want on webpage.
Now am looking to add a link to the results of the search so it takes me directly to the folder.
My code in c#:
protected void List_Dirs(string searchStr = null)
{
try
{
MainContentLocal.InnerHtml = "";
string[] directoryList = System.IO.Directory.GetDirectories("\\\\myfiles\\Web");
int x = 0;
foreach (string directory in directoryList)
{
if (searchStr != null && searchStr.Length > 1)
{
UserInfo.Text = "Your Search for : <strong>" + SearchPhrase.Text + "</strong> returns ";
if(directoryP.ToLower().Contains(searchStr.ToLower()))
{
MainContentLocal.InnerHtml += directoryP + "<br />";
x++;
}
}
else
{
MainContentLocal.InnerHtml += directoryP + "<br />";
}
if (searchStr != null && searchStr.Length > 1)
{
UserInfo.Text += "<strong>" + x.ToString() + "</strong> results";
UserInfo.CssClass = "userInfo";
}
}
catch(Exception DirectoryListExp)
{
MainContentLocal.InnerHtml = DirectoryListExp.Message;
}
}
When i enter something is search i will get a list of folders like:
Your Search for : project returns 2 results
job234 project234 Awards
job323 project game
now is there any way for me to click the result so i can open a window explore on the webpage
Thanks
You can create links like project234.
string folder = "\\\\myfiles\\Web";
if (string.IsNullOrWhiteSpace(Request["folder"])) {
// Folder clicked
folder = string.Format("{0}{1}", folder, Request["folder"]);
Process.Start(folder);
}
string[] directoryList = System.IO.Directory.GetDirectories(folder);
Then it will open it on the server. So if it really is local, than it will work. If there is no security problem. But I'm not sure. You can also use file:// links (as Ryan Mrachek notes), but browsers are not happy to let you open them.
If your result is a file, you can open that file programmatically through the Process class by invoking Process.Start("C:\\MyResults.txt"). This will open the results in the default text editor. In the same way, you can also open a web page by inserting passing a Url to Process.Start. I hope this is what wanted.
our file urls are malformed. It should be:
file:///c:/folder/
Please refer to The Bizarre and Unhappy Story of File URLs.
This works for me:
link
When you click Link, a new Windows Explorer window is opened to the specified location. But as you point out, this only works from a file:// URL to begin with.
A detailed explanation of what is going on can be found here. Basically this behavior by design for IE since IE6 SP1/SP2 and the only way you can change it is by explicitly disabling certain security policies using registry settings on the local machine.
So if you're an IT admin and you want to deploy this for your internal corporate LAN, this might be possible (though inadvisable). If you're doing this on some generic, public-facing website, it seems impossible.

webbrowsercontrol issue, clear cache not working?

I'm using a webbrowsercontrol to show .pdf's stored locally. At button press I want the webbrowser to show an empty page/nothing and I want to move the .pdf to a different folder. First I tried navigating to "" before moving but my .pdf was used by another process. Google told me that I probably needed to clear the browser's cache to be able to move it. I did so using the code found here: http://www.gutgames.com/post/Clearing-the-Cache-of-a-WebBrowser-Control.aspx and I even tried the alternative code line found in comment nr 2, but none of these let me move my .pdf, it's still used by another process.
What can/should I do to be able to move the file? Have I forgotten something?
At the second File.Move is where I get the error:
webBrowser1.Navigate("");
WebBrowserHelper.ClearCache();
if (calConv != "")
{
File.Move(forsDir + calConv + ".cal", forsDir + calConv.Replace("ToDo\\", "") + ".cg4");
File.Move(forsDir + calConv + ".pdf", forsDir + calConv.Replace("ToDo\\", "") + ".pdf");
}
This is how to show the PDF without using the webcontrol, using Adobe Reader instead:
Download the Acrobat SDK from http://www.adobe.com/devnet/acrobat/downloads.html
In your project add a reference to two dlls from the SDK - AxInterop.AcroPDFLib.dll and Interop.AcroPDFLib.dll
In your form's constructor add the Adobe previewer control:
// Check if the user has Adobe Reader installed, if not you could show a link to Adobe Reader installer
if (Type.GetTypeFromProgID("AcroPDF.PDF") == null)
{
pnlGetAdobe.Visible = pnlGetAdobe.Enabled = true;
}
else
{
try
{
// Initialize the Adobe control
axAcroPDF1 = new AxAcroPDF();
axAcroPDF1.Dock = DockStyle.Fill;
axAcroPDF1.Enabled = true;
axAcroPDF1.Location = new Point(0, 25);
axAcroPDF1.Name = "axAcroPDF1";
axAcroPDF1.OcxState = (AxHost.State)new ComponentResourceManager(typeof(JasperPdfReport)).GetObject("axAcroPDF1.OcxState");
axAcroPDF1.Size = new Size(634, 393);
axAcroPDF1.TabIndex = 1;
pnlCenter.Controls.Add(axAcroPDF1); // Add it to a container or instead directly to your form with this.Controls.Add(axAcroPDF1)
axAcroPDF1.BringToFront();
}
catch (COMException cex)
{
axAcroPDF1.Dispose();
axAcroPDF1 = null;
MessageBox.Show(cex.ToString());
}
catch (Exception ex)
{
axAcroPDF1.Dispose();
axAcroPDF1 = null;
MessageBox.Show(ex.ToString());
}
}
And finally load your PDF file into the control:
if (axAcroPDF1 != null && File.Exists(pdfFilename))
{
axAcroPDF1.setShowToolbar(false);
axAcroPDF1.setView("FitH");
axAcroPDF1.setLayoutMode("SinglePage");
// Load the PDF into the control
axAcroPDF1.LoadFile(pdfFilename);
axAcroPDF1.src = pdfFilename;
// Show it
axAcroPDF1.Show();
axAcroPDF1.Refresh();
}

Categories