Open PDF using C#-- Windows 8 Store Application - c#

I want to be able to open a PDF using the native Windows Reader Application when a user clicks on a button. So far I am able to use the following code to successfully open files that end with the (.PNG) extension. However, when I let the link to open the (.PDF) file I get the following error.
The system cannot find the file specified. (Exception from HRESULT: 0x80070002)
The file destination is correct.
Here is my code:
private async void btnLoad_Click(object sender, RoutedEventArgs e)
{
// Path to the file in the app package to launch
string imageFile = #"Data\Healthcare-Flyer.pdf";
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(imageFile);
if (file != null)
{
// Set the option to show the picker
var options = new Windows.System.LauncherOptions();
options.DisplayApplicationPicker = true;
// Launch the retrieved file
bool success = await Windows.System.Launcher.LaunchFileAsync(file, options);
if (success)
{
// File launched
}
else
{
// File launch failed
}
}
else
{
// Could not find file
}
}
}

When you add PDF document in project, you have to change it's build action.
Right click on PDF document.
Click on properties.
Change Build Action from None to Content

Related

How can I open a .pdf file in the browser from a Xamarin UWP project?

I have a Xamarin Project where I generate a .pdf file from scratch and save it in my local storage. This works perfectly fine and can find it and open it in the disk where I saved it. However, I need to open the .pdf file immediately after creation programmatically.
I already tried different variations using Process and ProcessStartInfo but these just throw errors like "System.ComponentModel.Win32Exception: 'The system cannot find the file specified'" and "'System.PlatformNotSupportedException'".
This is basically the path I am trying to open using Process.
var p = Process.Start(#"cmd.exe", "/c start " + #"P:\\Receiving inspection\\Inspection Reports\\" + timestamp + ".pdf");
I also tried ProcessStartInfo using some variations but I'm getting the same errors all over and over.
var p = new Process();
p.StartInfo = new ProcessStartInfo(#"'P:\\Receiving inspection\\Inspection Reports\\'" + timestamp + ".pdf");
p.Start();
The better way is that use LaunchFileAsync method to open file with browser. You could create FileLauncher DependencyService to invoke uwp LaunchFileAsync method from xamarin share project.
Interface
public interface IFileLauncher
{
Task<bool> LaunchFileAsync(string uri);
}
Implementation
[assembly: Dependency(typeof(UWPFileLauncher))]
namespace App14.UWP
{
public class UWPFileLauncher : IFileLauncher
{
public async Task<bool> LaunchFileAsync(string uri)
{
var file = await Windows.Storage.StorageFile.GetFileFromPathAsync(uri);
bool success = false;
if (file != null)
{
// Set the option to show the picker
var options = new Windows.System.LauncherOptions();
options.DisplayApplicationPicker = true;
// Launch the retrieved file
success = await Windows.System.Launcher.LaunchFileAsync(file, options);
if (success)
{
// File launched
}
else
{
// File launch failed
}
}
else
{
// Could not
}
return success;
}
}
}
Usage
private async void Button_Clicked(object sender, EventArgs e)
{
await DependencyService.Get<IFileLauncher>().LaunchFileAsync("D:\\Key.pdf");
}
Please note if you want to access D or C disk in uwp, you need add broadFileSystemAccess capability. for more please refer this .
Update
If the UWP files are network based, not local zone based, you could use Xamarin.Essentials to open file with browser. And you must specify the privateNetworkClientServer capability in the manifest. For more please refer this link.

PDF not opening on WP8 device

I have few pdf in a folder say Data/PDF/abc.pdf.
I am trying to open PDF with the below code:
private async void LaunchPDFNew(string name)
{
string imageFile = #"Data/PDF/"+name+".pdf";
// Get the image file from the package's image directory
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(imageFile);
if (file != null)
{
bool success = await Windows.System.Launcher.LaunchFileAsync(file, options);
if (success)
{
// File launched
Debug.WriteLine("File Launched");
}
else
{
// File launch failed
Debug.WriteLine("File Launched Failed");
}
}
else
{
// Could not find file
Debug.WriteLine("Could not find the file");
}
}
It gives me Error:
A first chance exception of type 'System.ArgumentException' occurred in mscorlib.ni.dll
An exception of type 'System.ArgumentException' occurred in mscorlib.ni.dll and wasn't handled before a managed/native boundary
I have tried with the solution given in below link as well
Launching PDF reader on windows phone 8
But neither of them is working.How to fix this ?
For all those people where they are not able to open the PDF.
1) Assming there's a file called "abc.pdf" in the project, with the Build Action set to Content, with Copy to Output Directory set to Copy if Newer)
2) If the pdf file is in the directory then use \ and not /, so
string file = #"Data/PDF/"+name+".pdf";
should be
string file = #"Data\PDF\"+name+".pdf";
3) And finally use this:
private async void LaunchPDF(string name)
{
string file = #"Data\PDF\"+name+".pdf";
// Get the image file from the package's image directory
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(imageFile);
if (file != null)
{
bool success = await Windows.System.Launcher.LaunchFileAsync(file);
if (success)
{
// File launched
Debug.WriteLine("File Launched");
}
else
{
// File launch failed
Debug.WriteLine("File Launched Failed");
}
}
else
{
// Could not find file
Debug.WriteLine("Could not find the file");
}
}

Open A PDF file on button click

I want to open a pdf file in winRT app(metro style app) by clicking on a button the file should open in windows8 default reader. I tried this code, where button click method name is DefaultLaunch_click():
async void DefaultLaunch_click()
{
// Path to the file in the app package to launch
string imageFile = #"images\ret.png";
// Get the image file from the package's image directory
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(imageFile);
if (file != null)
{
// Set the recommended app
var options = new Windows.System.LauncherOptions();
options.PreferredApplicationPackageFamilyName = “Contoso.FileApp_8wknc82po1e”;
options.PreferredApplicationDisplayName = “Contoso File App”;
// Launch the retrieved file pass in the recommended app
// in case the user has no apps installed to handle the file
bool success = await Windows.System.Launcher.LaunchFileAsync(file, options);
if (success)
{
// File launched
}
else
{
// File launch failed
}
}
else
{
// Could not find file
}
}
It worked for .png file but i want for .pdf file i replaced 1.png with M.pdf(after including it in images folder) and set the build content of M.pdf to Embedded Resource , run the program but it showed error that
**The system cannot find the file specified. (Exception from HRESULT: 0x80070002)**
This code works for me after I set PDF file build action to content and copy always to output directory.
private async void Button_Click(object sender, RoutedEventArgs e)
{
string imageFile = #"images\somepdffile.pdf";
// Get the image file from the package's image directory
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(imageFile);
if (file != null)
{
bool success = await Windows.System.Launcher.LaunchFileAsync(file, options);
if (success)
{
// File launched
}
else
{
// File launch failed
}
}
else
{
// Could not find file
}
}

Cant Unzip files from web application?

I am trying to unzip a downloaded file with Ionic.Zip Dll.
My code works in a windows application but it wont work in my Web application.
The code runs with no errors but when i check the folder there is still the Ziped downloaded file with no extractions.
Is there any specificity things a web application needs to do this??
private void MyExtract()
{
string zipToUnpack = "C:\\Users\\Shaun\\Desktop\\RescommTestData\\downloadfile.zip";
string unpackDirectory = "ExtractedFiles"; //used to create a file to extract files to
using (ZipFile zip1 = ZipFile.Read(zipToUnpack))
{
// here, we extract every entry, but we could extract conditionally
// based on entry name, size, date, checkbox status, etc.
foreach (ZipEntry e in zip1)
{
e.Extract(unpackDirectory, ExtractExistingFileAction.OverwriteSilently);
// e.Extract(ExtractExistingFileAction.OverwriteSilently);
}
}
try
{
//File.Delete("C:\\Users\\Shaun\\Desktop\\downloadfile.zip");
MessageBox.Show("Unpacked photos and data file into ExtractedFiles folder in bin/Debug");
}
catch (Exception)
{
MessageBox.Show("Could not delete ZIP!");
Environment.Exit(1);
}

Simple silverlight open-file-dialog errors

A while back I wrote a silverlight user control which had a csv import/export feature. This has been working fine, until recently I discovered it erroring in one scenario. This may have been due to moving to Silverlight 3.
The Error:
Message: Unhandled Error in Silverlight 2 Application
Code: 4004
Category: ManagedRuntimeError
Message: System.Security.SecurityException: Dialogs must be user-initiated.
at System.Windows.Controls.OpenFileDialog.ShowDialog()
at MyControl.OpenImportFileDialog()
at ...
The Code:
private void BrowseFileButton_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(lblFileName.Text))
{
if (MessageBox.Show("Are you sure you want to change the Import file?", "Import", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
{
return;
}
}
EnableDisableImportButtons(false);
var fileName = OpenImportFileDialog();
lblFileName.Text = fileName ?? string.Empty;
EnableDisableImportButtons(true);
}
private string OpenImportFileDialog()
{
var dlg = new OpenFileDialog { Filter = "CSV Files (*.csv)|*.csv" };
if (dlg.ShowDialog() ?? false)
{
using (var reader = dlg.File.OpenText())
{
string fileName;
//process the file here and store fileName in variable
return fileName;
}
}
}
I can open an import file, but if i want to change the import file, and re-open the file dialog, it errors. Does anyone know why this is the case?
Also, I am having trouble debugging because placing a breakpoint on the same line (or prior) to the dlg.ShowDialog() call seems to cause this error to appear as well.
Any help would be appreciated?
You do two actions on one user click.
You show a messagebox which effectively uses your permission to show a dialog on user action.
You then try to show the dialog, since this is a second dialog on user action it's not allowed.
Get rid of the confirmation dialog and you'll be fine.
Remove Break Points before if (dlg.ShowDialog() ?? false) code will run its work for me.

Categories