Appium Android: How to test pdf displayed inside WebView - appium

In Android, I want to test PDF which contains terms and conditions, but this displayed inside WebView. I am able to switch to WebView, I am using below code.
String strWebContextName = getContexts().stream().filter(ctx -> ctx.contains(“WEBVIEW_”)).findAny().orElse(null);
if (Objects.nonNull(strWebContextName)) {
((AndroidDriver) getBaseMobileDriver()).context(strWebContextName);
}
Then locate the script tag and get the content
#FindBy(xpath = “//script[#type=“text/javascript” and contains(text(),”_init")]")
private WebElement webElementPdfPath;
String htmlCode = (String) ((JavascriptExecutor) getBaseMobileDriver()).executeScript(“return arguments[0].innerHTML;”, webElementPdfPath);
After this I don’t know how to proceed? Please help

In my experience with verifying PDF's in a WebView is that there is only limited you can search for with selectors. I'm used to only class or type attributes of the PDF container. I have never been able to search for specific text in an PDF with XPath (PDF's are also not part of the HTML but more an extension which opens the document).
Try a simpler XPath: //script[#type='text/javascript']. This way you know the PDF is opened, but that's all.
I've done this with desktop browsers as well. For browsers, there is no way to identify inner PDF elements, but only limited to: //embed[#type='application/x-google-chrome-pdf']. If I needed to verify the PDF with conditions I've used SikuliX image recognition for instance.

Related

Printing from a Xamarin.Forms app

I'm all new to Xamarin and I'm currently working on a sample or a "prove of concept" app using Xamarin.Forms.
I'm supposed to perform a print task from this app though I'm not at this point sure what to print yet (the screen, content of a label, a file etc.).
Either way, what is the easiest way to print from a Xamarin.Forms app?
(current target is primarily Android 4.4+).
I hope this isn't too complicated :)
EDIT:
Ok let me just update this post as the original text might be a bit ambitious/vague.
I have a Xamarin.Forms project (+ an Android part) and I have some HTML available in the XF part of the project that I need to get into a WebView and print it.
From what I understand, the thing with the WebView has to be done on the Android part of the project due to the fact that this is where the printing will be handled.
I was hoping this could be done from code since I don't really need to display the WebView, just print it's content.
The Android part of the project has only the MainActivity and no layouts or XAML files.
I don't know where to add the WebView or how to access it (other than DependecyService seems to be a buzz word here) so I'm kinda stuck here.
I'm thinking that this task should be rather trivial to someone with a little more Xamarin experience than me.
Every platform XF supports has it's own mechanism for printing. XF does not provide any abstractions for printing in a cross-platform manner. You will need to write printing logic for each layer and expose it to XF using DependencyService (or some other DI engine).
Here is a good example, of course, using dependency service:
https://codemilltech.com/xamarin-forms-e-z-print/
I so wanted to do this but it was too hard. Finally built it into Forms9Patch - a MIT licensed open source project.
Verifying that Printing is available
Before printing, you should verify that printing is available on your device. To do so, call:
if (Forms9Patch.PrintService.CanPrint)
{
// do the printing here
}
Print the contents of a Xamarin.Forms.WebView
using Forms9Patch;
...
var myWebView = new Xamarin.Forms.WebView
myWebView.Source = new HtmlWebViewSource
{
Html = "some HTML text here"
};
...
myWebView.Print("my_print_job_name");
Note that your WebView does not have to be attached to a Layout. This allows you to Print without having to display the WebView in your app’s UI.
Printing an HTML string
using Forms9Patch;
...
var myHtmlString = #"
<!DOCTYPE html>
<html>
<body>
<h1>Convert to PNG</h1>
<p>This html will be converted to a PNG, PDF, or print.</p>
</body>
</html>
";
...
myHtmlString.Print("my_print_job_name");
PLEASE NOTE: iOS sometimes places the page breaks in weird places. I have a StackOverflow Bounty on why this happens and how to fix it.
Using EmbeddedResource as a source for a Xamarin.Forms.WebView
This is sort of an experimental feature I’ve built that I’ve found it useful. As such the documentation is sparse. It allow you to put HTML content in a folder in your app’s EmbeddedResources folder and then use it as a source for a WebView. A much nicer solution than using platform specific approach provided by Xamarin. It also supports putting all of the HTML content into a zip file. Please take a look at the source code to see how it works.
You can handle the printing of lists/ invoices .. with the xfinium pdf component from xamarin componentstore. With that you create your _pdffile and then call the following method which starts the adobereader from where you can select a printer (in my case google cloudprint)
public void printPdfToCloud(string _pdffile)
{
try
{
var saveto = System.IO.Path.Combine(Android.OS.Environment.ExternalStorageDirectory.ToString(), "YourApp/"+_pdffile);
string file_path = saveto;
if (System.IO.File.Exists(file_path))
{
Android.Net.Uri pdfFile = Android.Net.Uri.FromFile(new Java.IO.File(file_path));
Intent pdfIntent = new Intent(Intent.ActionView);
pdfIntent.SetPackage("com.adobe.reader");
pdfIntent.SetDataAndType(pdfFile, "application/pdf");
pdfIntent.SetFlags(ActivityFlags.NoHistory);
StartActivity(pdfIntent);
}else
{
// give a note that the file does not exist
}
}
catch (Exception E)
{
// Do some Error dialog
}
}

"document" in mozilla extension js modules?

I am building Firefox extension, that creates single XMPP chat connection, that can be accessed from all tabs and windows, so I figured, that only way to to this, is to create connection in javascript module and include it on every browser window. Correct me if I am wrong...
EDIT: I am building traditional extension with xul overlays, not using sdk, and talking about those modules: https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules
So I copied Strophe.js into js module. Strophe.js uses code like this:
/*_Private_ function that creates a dummy XML DOM document to serve as
* an element and text node generator.
*/
[---]
if (document.implementation.createDocument === undefined) {
doc = this._getIEXmlDom();
doc.appendChild(doc.createElement('strophe'));
} else {
doc = document.implementation
.createDocument('jabber:client', 'strophe', null);
}
and later uses doc.createElement() to create xml(or html?) nodes.
All worked fine, but in module I got error "Error: ReferenceError: document is not defined".
How to get around this?
(Larger piece of exact code: http://pastebin.com/R64gYiKC )
Use the hiddenDOMwindow
Cu.import("resource://gre/modules/Services.jsm");
var doc = Services.appShell.hiddenDOMWindow.document;
It sounds like you might not be correctly attaching your content script to the worker page. Make sure that you're using something like tabs.attach() to attach one or more content scripts to the worker page (see documentation here).
Otherwise you may need to wait for the DOM to load, waiting for the entire page to load
window.onload = function ()
{
Javascript code goes here
}
Should take at least diagnose that issue (even if the above isn't the best method to use in production). But if I had to wager, I'd say that you're not attaching the content script.

Using printer name Adobe PDF

I have looked everywhere for this solution. The code below allows me to print to the printer, Adobe PDF, but what I want to do is automate the file name save as screen with a generic name and in a specific folder. For example, the file would be saved to C:\temp\tmpResize.pdf and I am having problems there.
var params = this.getPrintParams();
params.interactive=params.constants.interactionLevel.silent;
params.pageHandling=params.constants.handling.none;
params.fileName = "/c/temp/tmpResize.pdf";
params.printerName="Adobe PDF"
this.print(params);
Thanks for your help.

Populating Iframe with PDF - Using MVC [IE Issue]

Currently, I have an issue with populating an iframe that I have with a PDF document, but this issue only occurs in IE.
Basic Layout:
I have a screen that contains a list of items (attachments), which can be images, text or pdf. When the user clicks on one of these items - it will make a call to a controller action [ViewAttachment] which will return the requested item and display it in the iframe.
This currently works for all data types with the exception of PDFs in IE. (Firefox, Chrome etc. all display the PDF in the iframe without issue.)
I previously was using Adobe Reader 9, and recently upgraded to 10 in hopes of solving this issue. I'll attach some code to see if anyone has any suggestions as to how to possibly resolve this.
Code to Populate iframe: (Moved to two lines for readability)
$(".viewattachment").live('click',function ()
{
$("iframe#test").attr("src","<%=Url.Action("ViewAttachment","Images") %>?
attachment=" + $(this).next().val());
});
ViewAttachment Controller Action:
public ActionResult ViewAttachment(string attachmentGuid)
{
Attachment attachment= imageAgent.GetAttachment(attachmentGuid);
Stream resultStream = new MemoryStream();
resultStream = StorageProviders[attachment.ProviderName]
.ReadFile(attachment.FileReference);
resultStream.Position = 0;
FileStreamResult result = new FileStreamResult(resultStream,
attachment.ContentType);
return result;
}
Notes:
I've attempted toggling the "Display PDF in Browser" in Adobe Reader without any success.
Currently testing this for IE8.
When clicking on a PDF to view - the iframe simply remains at it's previous content and doesn't change at all.
After several different methods and iterations of testing - I determined that it was a conflict between IE8-9 and versions of Adobe Reader 9-10. I added the following meta tag to the window containing the iframe and it resolved all of the issues:
<meta http-equiv="X-UA-Compatible" content="IE=7" />
This should at least work until an update / fix is made.
Have you tried hitting the pdf url directly? If it loads within the browser, then you can narrow down the problem to the iframe. If Adobe Reader pops up, then you know its a problem with the IE Plugin.
I had the same problem working with spring mvc. I releazed that if I put the Iframe inside some tag, like 'util:panel', the iframe does not load de pdf content in IE 8. When I put the iFrame out of the tag, all work fine.

Save current webpage in Watin

I'm trying to save the full content of the current static web page, using the code from Show IE "Save As" dialog using Watin
So here it is:
IE ie = new IE("http://localhost");
// more code
//I expect out.html is the output file
FileDownloadHandler fileDownloadHandler = new FileDownloadHandler("out.html");
//I expect this line to popup the save as dialog box, but nothing happens
ie.AddDialogHandler(fileDownloadHandler);
//the program is blocked at this line, as it can't click anywhere
ie.Link("startDownloadLinkId").Click();
fileDownloadHandler.WaitUntilFileDownloadDialogIsHandled(15);
fileDownloadHandler.WaitUntilDownloadCompleted(200);
I also tried the code below, but it doesn't save all the page:
System.IO.StreamWriter file = new System.IO.StreamWriter("output.html");
file.Write(ie.Html);
Again, I need to save the webpage from Watin, and the result to be the same as saving it manually.
Thanks!
Here is how I do it:
File.WriteAllText("myfile.html",
(myIE.InternetExplorer as SHDocVw.InternetExplorer).Document.documentElement.outerHtml);
Assumes myIE is a WatiN IE element, of course.
If you're ever having difficulty finding how to do something with WatiN, I often find it helpful to google how to do it with an "Internet Explorer COM object". WatiN wraps the object, but it is exposed and able to be accessed!
Cheers!
Try to parse the html with html agility pack and save it, there are additional abilities that you can use...
using HtmlAgilityPack;
var htmldoc = new HtmlDocument();
htmldoc.LoadHtml(ie.Html);
htmldoc.Save(stream);
Link to agility pack

Resources