In the Java EE environment, I want to load an XML and XSL file, render the output to a browser window, and save the rendered page as PDF.
I would like to do it all programmatically. I was looking at HtmlUnit to use as a headless browser. That part seems to work, but does HtmlUnit have any API to invoke a "print" function or similar function to persisted the rendered output? I was thinking of some way to link it in with iText.
I would recommend trying out flying-saucer which in this case basically is a CSS/XHTML enabled iText wrapper.
I wrote a simple example below. Don't forget the necessary dependencies for HtmlUnit and flying-saucer.
//Set up a new WebClient using your favourite settings
WebClient webClient = new WebClient();
//Fetch page
HtmlPage page = webClient.getPage("url-to-target.resource");
//Set PDF target output file
String outputFile = "firstdoc.pdf";
OutputStream os = new FileOutputStream(outputFile);
//Set up flying-saucer IText based renderer
ITextRenderer renderer = new ITextRenderer();
//Create PDF
renderer.setDocumentFromString(page.asXml();
renderer.layout();
renderer.createPDF(os);
os.close();
If you're doing reporting in Java i highly recommend you to use Jasper Reports, it's relatively easy to use, you can design the report graphically and it can take XML as input and give you a report in many formats (including PDF).
Related
I tried to use (jp#gc - HtmlUnit Driver Config) to create a headless browser test using jmeter, but I get this error
Response message: com.gargoylesoftware.htmlunit.ScriptException: ReferenceError: "getComputedStyle" is not defined.
I read online and it suggest that jp#gc - HtmlUnit Driver Config doesn't support javascript. Is there a way I can fix this via jmeter? or is there any other option to do headless browser testing. I have linux server as load injector
Update:
I have a webdriver sampler to open google page
WDS.sampleResult.sampleStart() WDS.browser.get('http://google.com')
WDS.sampleResult.sampleEnd()
and have downloaded Phanton JS, but when I run it it doesn't show anything on the report. Should I add any other config?
HtmlUnit do not support very well JS.
I done many tests and used each one and i can say that PHANTOMJS is the best one with good support of all JS/CSS... have a beautiful renderer to have nice screenshots.
by code you can use it like this (you can download it from here http://phantomjs.org/download.html (phantomjs-1.9.8 is very stable)):
Capabilities caps = new DesiredCapabilities();
((DesiredCapabilities) caps).setJavascriptEnabled(true);
((DesiredCapabilities) caps).setCapability("takesScreenshot", true);
((DesiredCapabilities) caps).setCapability(
PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,
"your custom path\\phantomjs.exe"
);
WebDriver driver = new PhantomJSDriver(caps);
If you want to do that via JMeter GUI, you need to add before your Logic Controller an element JSR223 Sampler JSR223_Sampler
and inside the script panel :
org.openqa.selenium.Capabilities caps = new org.openqa.selenium.remote.DesiredCapabilities();
((org.openqa.selenium.remote.DesiredCapabilities) caps).setJavascriptEnabled(true);
((org.openqa.selenium.remote.DesiredCapabilities) caps).setCapability("takesScreenshot", true);
((org.openqa.selenium.remote.DesiredCapabilities) caps).setCapability(
org.openqa.selenium.phantomjs.PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,
"your custom path\\phantomjs.exe");
org.openqa.selenium.WebDriver driver = new org.openqa.selenium.phantomjs.PhantomJSDriver(caps);
org.apache.jmeter.threads.JMeterContextService.getContext().getCurrentSampler().getThreadContext()
.getVariables().putObject(com.googlecode.jmeter.plugins.webdriver.config.WebDriverConfig.BROWSER, driver);
Do not hesitate if you need more informations.
I am looking for a method to download automatically a file from a website.
Currently the process is really manual and heavy.
I go on a webpage, I enter my pass and login.
It opens a pop up, where I have to click a download button to save a .zip file.
Do you have any advice on how I could automate this task ?
I am on windows 7, and I can use mainly MS dos batch, or python. But I am open to other ideas.
You can use selenium web driver to automate the downloading. You can use below snippet for browser download preferences in java.
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("browser.download.folderList", 2);
profile.setPreference("browser.download.manager.showWhenStarting", false);
profile.setPreference("browser.download.dir", "C:\\downloads");
profile.setPreference("browser.helperApps.neverAsk.openFile","text/csv,application/x-msexcel,application/excel,application/x-excel,application/vnd.ms-excel,text/html,text/plain,application/msword,application/xml");
To handle the popup using this class when popup comes.
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_DOWN);
robot.keyRelease(KeyEvent.VK_DOWN);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
You'll want to take a look at requests (to fetch the html and the file), Beautifulsoup (to parse the html and find the links)
requests has built in auth: http://docs.python-requests.org/en/latest/
Beautifulsoup is quite easy to use: http://www.crummy.com/software/BeautifulSoup/bs4/doc/
Pseudocode: use request to download the sites html and auth. Go through the links by parsing. If a link meets the criteria -> save in a list, else continue. When all the links have been scrapped, go through them and download the file using requests (req = requests.get('url_to_file_here', auth={'username','password'}), if req.status_code in [200], file = req.text
If you can post the link of the site you want to download from, maybe we can do more.
How do you download data from an url in UWP? I'm used to using WebClient's DownloadData-method, but it can't be used anymore.
.NET for UWP does not have the WebClient class.
But you have several alternative ways to download the data from URL in UWP.
For example:
var request = WebRequest.CreateHttp("http://www.bing.com");
var donnetClient = new System.Net.Http.HttpClient();
var winrtClient = new Windows.Web.Http.HttpClient();
If you want to download the data at background, you can use the BackgroundDownloader class
I'm developing an app for Windows Phone 7 and I'm using a Phonegap template for it.
Everything looks perfect, but now I’m stuck trying to open a PDF file in the browser.
I tried the following but that doesn’t work because the url of the PDF exceeds the 2048 character limit (it’s a data url). This code runs after the deviceReady event was fired.
var ref = window.open('http://www.google.com', '_blank', 'location=no');
ref.addEventListener('loadstart', function () { alert(event.url); });
Now, I'm trying to save the PDF file to storage and then I'm trying to have it opened by the browser, but the browser doesn't show anything. I'm editing the InAppBrowser.cs code from cordovalib and I added the following lines before calling browser.Navigate(loc);
private void ShowInAppBrowser(string url)
{
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
FileStream stream = store.OpenFile("test.pdf", FileMode.Create);
BinaryWriter writer = new BinaryWriter(stream);
var myvar = Base64Decode("the big data url");
writer.Write(myvar);
writer.Close();
if (store.FileExists("test.pdf")) // Check if file exists
{
Uri loc = new Uri("test.pdf", UriKind.Relative);
...
}
}
This code is returning the following error:
Log:"Error in error callback: InAppBrowser1921408518 = TypeError: Unable to get value of the property 'url': object is null or undefined"
I don’t wanna use ComponentOne.
Any help would be greatly appreciated!
You cannot open pdf files from the isolated storage in the default reader for PDF files. If the file is online e.g. it has a URI for it, you can use WebBrowserTask to open it since that will download and open the file in Adobe Reader.
On Windows Phone 8 you actually can open your own file in default file reader for that extension, but I am not sure how that will help you since you target PhoneGap and Windows Phone 7.
Toni is correct. You could go and try to build your own viewer (which would be the same thing as using C1, but with more time involved). I worked on a port of iTextSharp and PDFSharp for WP7, but neither of which are PDF Viewers. They are good for creating PDFs and parsing them some (but to render them there is more work involved). This has been a personal quest of mine, but honestly the best I have gotten is to be able to extract some images from the PDF (and none of the text)
try this
var installedLocation = Windows.ApplicationModel.Package.Current.InstalledLocation;
var assets = await installedLocation.GetFolderAsync("Assets");
var pdf = await assets.GetFileAsync("metro.pdf");
Windows.System.Launcher.LaunchFileAsync(pdf);
This worked correctly on my Device.
Can anyone point me to a current example of how to use HTMLUnit to interact with a webpage (submit a form, click, etc) along with the current jars that work with the example? I donwloaded all the jars on the htmlunit page and all its dependent jars, and I keep getting NoSuchMethod errors, so I'm guessing I have mismatched jars.
Hi if you're having issues to set up HtmlUnit this answer might help How to setup HtmlUnit in an Eclipse project?
Regarding form submission and clicking, this is the example taken from the HtmlUnit documenation itself:
public void submittingForm() throws Exception {
final WebClient webClient = new WebClient();
// Get the first page
final HtmlPage page1 = webClient.getPage("http://some_url");
// Get the form that we are dealing with and within that form,
// find the submit button and the field that we want to change.
HtmlForm form = page1.getFormByName("myform");
HtmlSubmitInput button = form.getInputByName("submitbutton");
HtmlTextInput textField = form.getInputByName("userid");
// Change the value of the text field
textField.setValueAttribute("root");
// Now submit the form by clicking the button and get back the second page.
final HtmlPage page2 = button.click();
webClient.closeAllWindows();
}
HTMLUnit is integrated in Selenium WebDriver. http://www.seleniumhq.org/projects/webdriver/
the best advice that I can give you is, since you are working with Java, make it a Maven Project and add the dependencies for selenium.webdriver. Building the project as Maven avoids having common mistakes like saving the jars in a wrong directory or forgetting 1 jar