MonoTouch printing a local PDF file - c#

I have a MonoTouch application that generates some PDFs locally and then prints them to a network printer. To get this working I initially just added a PDF resource to the project that I could try and print but am having a heck of a time. When I print just HMTL or a string value everything is good but printing the PDF has me lost. When debugging it looks like the app is getting the proper URL.
Any help would be greatly appreciated and my sampled code is below:
public void PrintSomePDF ()
{
var printInfo = UIPrintInfo.PrintInfo;
printInfo.OutputType = UIPrintInfoOutputType.General;
printInfo.JobName = "Test: PDF Print";
string pdfFileName = "printthispdf_01.pdf";
NSUrl url = NSUrl.FromFilename(pdfFileName);
var printer = UIPrintInteractionController.SharedPrintController;
printer.PrintInfo = printInfo;
printer.PrintingItem = url.Path;
printer.ShowsPageRange = true;
printer.Present (true, (handler, completed, err) => {
if (!completed && err != null){
Console.WriteLine ("error");
}
});
}
I was able to resolve the problem with the way I passed in the NSUrl to the PrintingItem. Before I was passing in printer.PrintingItem = url.Path; which was basically just passing in a string of the path and not the actual shape of NSUrl.
printer.PrintingItem = url;

What I've always preferred to do (and this depends very much on the deployed device - in my case it was a server I controlled) was to just install a PDF printer and then it's as easy as printing any other kind of document.
Something like BullZip is free and allows you to write any settings for the print to a RunOnce.ini (xml) file to have a silent mode print with settings for the filename and so forth.
Obviously not a great solution if you don't have control of the system you're deploying to, but a solid and easy one if you do.

Related

c# printing through PDF drivers, print to file option will output PS instead of PDF

After struggling whole day, I identified the issue but this didn't solve my problem.
On short:
I need to open a PDF, convert to BW (grayscale), search some words and insert some notes nearby found words. At a first look it seems easy but I discovered how hard PDF files are processed (having no "words" concepts and so on).
Now the first task, converting to grayscale just drove me crazy. I didn't find a working solution either commercial or free. I came up with this solution:
open the PDF
print with windows drivers, some free PDF printers
This is quite ugly since I will force the C# users to install such 3'rd party SW but.. that is fpr the moment. I tested FreePDF, CutePDF and PDFCreator. All of them are working "stand alone" as expected.
Now when I tried to print from C#, obviously, I don't want the print dialog, just select BW option and print (aka. convert)
The following code just uses a PDF library, shown for clarity only.
Aspose.Pdf.Facades.PdfViewer viewer = new Aspose.Pdf.Facades.PdfViewer();
viewer.BindPdf(txtPDF.Text);
viewer.PrintAsGrayscale = true;
//viewer.RenderingOptions = new RenderingOptions { UseNewImagingEngine = true };
//Set attributes for printing
//viewer.AutoResize = true; //Print the file with adjusted size
//viewer.AutoRotate = true; //Print the file with adjusted rotation
viewer.PrintPageDialog = true; //Do not produce the page number dialog when printing
////PrinterJob printJob = PrinterJob.getPrinterJob();
//Create objects for printer and page settings and PrintDocument
System.Drawing.Printing.PrinterSettings ps = new System.Drawing.Printing.PrinterSettings();
System.Drawing.Printing.PageSettings pgs = new System.Drawing.Printing.PageSettings();
//System.Drawing.Printing.PrintDocument prtdoc = new System.Drawing.Printing.PrintDocument();
//prtdoc.PrinterSettings = ps;
//Set printer name
//ps.PrinterName = prtdoc.PrinterSettings.PrinterName;
ps.PrinterName = "CutePDF Writer";
ps.PrintToFile = true;
ps.PrintFileName = #"test.pdf";
//
//ps.
//Set PageSize (if required)
//pgs.PaperSize = new System.Drawing.Printing.PaperSize("A4", 827, 1169);
//Set PageMargins (if required)
//pgs.Margins = new System.Drawing.Printing.Margins(0, 0, 0, 0);
//Print document using printer and page settings
viewer.PrintDocumentWithSettings(ps);
//viewer.PrintDocument();
//Close the PDF file after priting
What I discovered and seems to be little explained, is that if you select
ps.PrintToFile = true;
no matter C# PDF library or PDF printer driver, Windows will just skip the PDF drivers and instead of PDF files will output PS (postscript) ones which obviously, will not be recognized by Adobe Reader.
Now the question (and I am positive that others who may want to print PDFs from C# may be encountered) is how to print to CutePDF for example and still suppress any filename dialog?
In other words, just print silently with programmatically selected filename from C# application. Or somehow convince "print to file" to go through PDF driver, not Windows default PS driver.
Thanks very much for any hints.
I solved conversion to grayscale with a commercial component with this post and I also posted there my complete solution, in care anyone will struggle like me.
Converting PDF to Grayscale pdf using ABC PDF

Print Direct from Web application to local printer

My Requirement is to print invoices in pdf direct to local printer from web application developed in .net mvc framework.
I need to do exact like shipstation is doing with SHIPSTATION CONNECT
SHIPSTATION CONNECT
Does it use process like
REMOTE PRINTER SHARING CODEPROJECT
or using WMI library to share printer remotely.
Any expert thought will help me and my programmer to build the solution.I am not expecting code or spoon feeding but like to know the process and way to start on this in right direction.
Thanks in advance for the help!
regards
check printnode.com might be of some help.Seems like doing same thing what you want.The service is not free chargeable or alternatively you can build same using google cloud print.
you can write javascript function that print from local printer,
w=window.open();
w.document.open();
w.document.write("<html><head></head><body>");
w.document.write("HI");
w.document.write("</body></html>");
w.document.close();
w.print();
w.close();
working example:
http://jsfiddle.net/xwgq5ap4/
if you want to print from the server you need to send a request for the server for example :
www.mysite.com/print.aspx?file=invoice.pdf
to print it by the server you have 2 solutions the first is calling to other process to accomplish it like you can see in this answer:
Print Pdf in C#
the second is write your own implementation using PrintDocument namespace for example:
namespace PrintPDF
{
class Program
{
static void Main(string[] args)
{
PdfDocument doc = new PdfDocument();
doc.LoadFromFile("sample.pdf");
//Use the default printer to print all the pages
//doc.PrintDocument.Print();
//Set the printer and select the pages you want to print
PrintDialog dialogPrint = new PrintDialog();
dialogPrint.AllowPrintToFile = true;
dialogPrint.AllowSomePages = true;
dialogPrint.PrinterSettings.MinimumPage = 1;
dialogPrint.PrinterSettings.MaximumPage = doc.Pages.Count;
dialogPrint.PrinterSettings.FromPage = 1;
dialogPrint.PrinterSettings.ToPage = doc.Pages.Count;
if (dialogPrint.ShowDialog() == DialogResult.OK)
{
doc.PrintFromPage = dialogPrint.PrinterSettings.FromPage;
doc.PrintToPage = dialogPrint.PrinterSettings.ToPage;
doc.PrinterName = dialogPrint.PrinterSettings.PrinterName;
PrintDocument printDoc = doc.PrintDocument;
dialogPrint.Document = printDoc;
printDoc.Print();
}
}
}
}
original taken from free 3rd party library

Selenium WebDriver file upload browse button c#

I have problem with browse button and switching to file dialog. I cannot use my file path control and just send there my string with file path and file itself, as it's readonly and in fact some behind control is my input filepath.
Here's my code
driver.FindElement(By.Id("browseButton")).Click();
driver.SwitchTo().ActiveElement().SendKeys(filepath);
Above code fills my control for file path, as i can see that on UI. But my open file dialog is still opened and i do not know how to close it and submit my upload.
Uploading files in Selenium can be a pain, to say the least. The real problem comes from the fact that it does not support dialog boxes such as file upload and download.
I go over this in an answer to another question, so I will just copy/paste my answer from there here. The code examples should actually be relevant in your case, since you are using C#:
Copied from previous answer on question here:
Selenium Webdriver doesn't really support this. Interacting with non-browser windows (such as native file upload dialogs and basic auth dialogs) has been a topic of much discussion on the WebDriver discussion board, but there has been little to no progress on the subject.
I have, in the past, been able to work around this by capturing the underlying request with a tool such as Fiddler2, and then just sending the request with the specified file attached as a byte blob.
If you need cookies from an authenticated session, WebDriver.magage().getCookies() should help you in that aspect.
edit: I have code for this somewhere that worked, I'll see if I can get ahold of something that you can use.
public RosterPage UploadRosterFile(String filePath){
Face().Log("Importing Roster...");
LoginRequest login = new LoginRequest();
login.username = Prefs.EmailLogin;
login.password = Prefs.PasswordLogin;
login.rememberMe = false;
login.forward = "";
login.schoolId = "";
//Set up request data
String url = "http://www.foo.bar.com" + "/ManageRoster/UploadRoster";
String javaScript = "return $('#seasons li.selected') .attr('data-season-id');";
String seasonId = (String)((IJavaScriptExecutor)Driver().GetBaseDriver()).ExecuteScript(javaScript);
javaScript = "return Foo.Bar.data.selectedTeamId;";
String teamId = (String)((IJavaScriptExecutor)Driver().GetBaseDriver()).ExecuteScript(javaScript);
//Send Request and parse the response into the new Driver URL
MultipartForm form = new MultipartForm(url);
form.SetField("teamId", teamId);
form.SetField("seasonId", seasonId);
form.SendFile(filePath,LoginRequest.sendLoginRequest(login));
String response = form.ResponseText.ToString();
String newURL = StaticBaseTestObjs.RemoveStringSubString("http://www.foo.bar.com" + response.Split('"')[1].Split('"')[0],"amp;");
Face().Log("Navigating to URL: "+ newURL);
Driver().GoTo(new Uri(newURL));
return this;
}
Where MultiPartForm is:
MultiPartForm
And LoginRequest/Response:
LoginRequest
LoginResponse
The code above is in C#, but there are equivalent base classes in Java that will do what you need them to do to mimic this functionality.
The most important part of all of that code is the MultiPartForm.SendFile method, which is where the magic happens.
One of the many ways to do that is to remove the disable attribute and then use typical selenium SendKeys() to accomplish that
public void test(string path)
{
By byId = By.Id("removeAttribute");
const string removeAttribute = #"document.getElementById('browseButton').removeAttribute('disabled');";
((IJavaScriptExecutor)Driver).ExecuteScript(removeAttribute);
driver.FindElement(byId).Clear();
driver.FindElement(byId).SendKeys(path);
}
You can use this Auto IT Script to Handle File Upload Option.
Auto IT Script for File Upload:
AutoItSetOption("WinTitleMatchMode","2") ; set the select mode to
Do
Sleep ("1000")
until WinExists("File Upload")
WinWait("File Upload")
WinActivate("File Upload")
ControlFocus("File Upload","","Edit1")
Sleep(2000)
ControlSetText("File Upload" , "", "Edit1", $CmdLineRaw)
Sleep(2000)
ControlClick("File Upload" , "","Button1");
Build and Compile the above code and place the EXE in a path and call it when u need it.
Call this Once you click in the Browse Button.
Process p = System.Diagnostics.Process.Start(txt_Browse.Text + "\\File Upload", DocFileName);
p.WaitForExit();

Set page orientation when printing from the WebBrowser control in c#. (NON WPF Application)

Is it possible to change the orientation on the printer when using the webbrowser control? I need to change it to landscape. If I need to change the printer defaults for the printer itself that would be ok to as I would just set them back after I was done. (That's what I currently have to do with printing to a non-default printer).
I currently use this to temporarealy set the default printer, then set it back when I'm done with my print job...
private string SetDefaultPrinter(string newDefaultPrinter)
{
//Get the list of configured printers:
string strQuery = "SELECT * FROM Win32_Printer";
string currentDefault = string.Empty;
System.Management.ObjectQuery oq = new System.Management.ObjectQuery(strQuery);
System.Management.ManagementObjectSearcher query1 = new System.Management.ManagementObjectSearcher(oq);
System.Management.ManagementObjectCollection queryCollection1 = query1.Get();
System.Management.ManagementObject newDefault = null;
foreach (System.Management.ManagementObject mo in queryCollection1)
{
System.Management.PropertyDataCollection pdc = mo.Properties;
if ((bool)mo["Default"])
{
currentDefault = mo["Name"].ToString().Trim();
if (newDefaultPrinter == null || newDefaultPrinter == string.Empty)
{
//Just need to know the default name
break;
}
}
else if (mo["Name"].ToString().Trim() == newDefaultPrinter)
{
//Save this for later
newDefault = mo;
}
}
//Reset the default printer
if (newDefault != null)
{
//Execute the method
System.Management.ManagementBaseObject outParams = newDefault.InvokeMethod("SetDefaultPrinter", null, null);
}
return currentDefault;
}
Anyone know how to change the orientation?
You can do this by using IE print templates. There are not too much documentation on this, but here below is another stack-overflow post that suggests some useful links on this regards, and it actually helped me a lot:
WebBrowser print settings
The most useful part was suggesting to view the standard IE print template by navigating to the below URL inside IE:
res://ieframe.dll/preview.dlg
And also you can view a related JavaScript file by navigating to the below URL inside IE:
res://ieframe.dll/preview.js
Those two files helped me a lot to understand what is going on in the background, and by changing the "Printer.orientation" value inside the "preview.js" file, I could successfully change the orientation of the printed HTML document.
//EDIT:
I was testing it wrong. The documentation referring to this registry key is for windows CE... So the correct answer is that it is not possible, as "explained" in the documentation: http://support.microsoft.com/kb/236777
A possible workaround is to rotate the whole page through css (transform:rotate(90deg)), but the relative position keeps being the old one, so for multiple pages is just a mess.
It is incredible that something so basic can't be done...
//OLD ANSWER:
I was looking for the same and finally found that you really can't change the printer settings (page orientation, header, footer, margins...) directly with the webbrowser component, the only way to do it is changing the registry key to set the default behaviour of internet explorer.
For the page orientation it would be:
Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true).SetValue("PageOrientation", 2);
You should keep the old value and restore it after printing.

Printing A PDF Automatically to a specific printer and tray

I have a C# application that When the user clicks Print the application creates a PDF in memorystream using ITextSharp. I need to print this PDF automatically to a specific printer and tray.
I have searched for this but all i can find is using javascript, but it doesn't print to a specific tray.
Does anyone have an examples of doing this?
Thank you.
You can change printer tray with this code.
string _paperSource = "TRAY 2"; // Printer Tray
string _paperName = "8x17"; // Printer paper name
//Tested code comment. The commented code was the one I tested, but when
//I was writing the post I realized that could be done with less code.
//PaperSize pSize = new PaperSize() //Tested code :)
//PaperSource pSource = new PaperSource(); //Tested code :)
/// Find selected paperSource and paperName.
foreach (PaperSource _pSource in printDoc.PrinterSettings.PaperSources)
if (_pSource.SourceName.ToUpper() == _paperSource.ToUpper())
{
printDoc.DefaultPageSettings.PaperSource = _pSource;
//pSource = _pSource; //Tested code :)
break;
}
foreach (PaperSize _pSize in printDoc.PrinterSettings.PaperSizes)
if (_pSize.PaperName.ToUpper() == _paperName.ToUpper())
{
printDoc.DefaultPageSettings.PaperSize = _pSize;
//pSize = _pSize; //Tested code :)
break;
}
//printDoc.DefaultPageSettings.PaperSize = pSize; //Tested code :)
//printDoc.DefaultPageSettings.PaperSource = pSource; //Tested code :)
in the past I spent a lot of time searching the web for solutions to print pdf files to specific printer trays.
My requirement was: collect several pdf files from server directory and send each file to a different printer tray in a loop.
So I have tested a lot of 3rd party tools (trials) and best practices found in web.
Generally all theese tools can be divide into two classifications: a) send pdf files to printer in a direct way (silent in UI) or b) open pdf files in UI using a built-in pdf previewer working with .Net-PrintDocument.
The only solution that fix my requirement was PDFPrint from veryPdf (drawback: it´s not priceless, but my company bought it). All the other tools and solutions didn´t work reliable, that means: calling their print-routines with parameter e.g. id = 258 (defines tray 2; getting from installed printer) but printing the pdf file in tray 3 or pdf was opened in print previewer (UI) with lost images or totally blank content and so on..
Hope that helps a little bit.
There is a tool called pdfprint:
http://www.verypdf.com/pdfprint/index.html
And here they discuss some solutions:
http://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/da99765f-2706-4bb6-aa0e-b90730294cb4

Categories

Resources