Cannot run simple script with WebView Universal Windows App - windows-phone

I have simple html file (save in project) load on to WebView. It load success and display "Hello World" header.
File index.html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>ABC</title>
<script>
function SayHello() {
return "hello";
};
</script>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
Load to WebView
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
webView.Navigate(new Uri("ms-appx-web:///index.html", UriKind.RelativeOrAbsolute));
// Exception below line
var data = await webView.InvokeScriptAsync("eval", new List<string> { "SayHello();" });
Debug.WriteLine(data);
}
I don't understand why this happen. It success run on Google Chrome. Am I miss something here?

MSDN about Navigate method:
Loads the HTML content at the specified Uniform Resource Identifier
(URI).
When you call the method, it doesn't instantly load the content, it may take some time. You need to listen to the DOMContentLoaded event and then run the script when page is actually loaded into the WebView.
webView1.DOMContentLoaded += webView1_DOMContentLoaded;
...
...
private async void webView1_DOMContentLoaded(WebView sender, WebViewDOMContentLoadedEventArgs args)
{
var data = await webView.InvokeScriptAsync("eval", new List<string> { "SayHello();" });
Debug.WriteLine(data);
}

I think you should go to Manifest profile in URI,
Windows Runtime Access= All
Type = Include

Related

ASP.NET Core Web API: 405 - HTTP verb used to access this page is not allowed

In ASP.NET Core-6 application, I have this code for PUT Request:
Service:
public Response<object> AppendStatus(string acctNumber, string appendName)
{
var response = new Response<object>();
try
{
using (AseConnection con = new AseConnection(aseConnection))
{
AseCommand cmd = new AseCommand("sp_append", con);
cmd.CommandType = CommandType.StoredProcedure;
var managerId = CodeUsername.Username;
cmd.Parameters.AddWithValue("#AggregatorId", managerId);
cmd.Parameters.AddWithValue("#AcctNo", acctNumber);
cmd.Parameters.AddWithValue("#ManagerName", appendName);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
response.Success = true;
}
catch (Exception ex)
{
_logger.Error($"An Error occured " + ex.ToString());
response.Success = false;
}
return response;
}
Then I have this controller:
BaseController:
[Produces("application/json")]
[ApiController]
public class BaseApiController : ControllerBase
{
}
[Consumes("application/json")]
[Authorize]
[Route("api/v1/[controller]")]
public class ManagerController : BaseApiController
{
private readonly ILogger<ManagerControllerr> _logger;
private IAccountsTransService _accountsTransService;
public ManagerController(
ILogger<ManagerController> logger,
IAccountsTransService accountsTransService
)
{
_logger = logger;
_accountsTransService = accountsTransService; }
[HttpPut]
[Route("account/append")]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public ActionResult<Response<object>> AppendAccount(string acctNumber, string appendName)
{
var result = _accountsTransService.AppendAccount(acctNumber, appendName);
return result;
}
The application is deployed on IIS.
When user submits, the error comes up:
Response body:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<title>405 - HTTP verb used to access this page is not allowed.</title>
<style type="text/css">
<!--
body{margin:0;font-size:.7em;font-family:Verdana, Arial, Helvetica, sans-serif;background:#EEEEEE;}
fieldset{padding:0 15px 10px 15px;}
h1{font-size:2.4em;margin:0;color:#FFF;}
h2{font-size:1.7em;margin:0;color:#CC0000;}
h3{font-size:1.2em;margin:10px 0 0 0;color:#000000;}
#header{width:96%;margin:0 0 0 0;padding:6px 2% 6px 2%;font-family:"trebuchet MS", Verdana, sans-serif;color:#FFF;
background-color:#555555;}
#content{margin:0 0 0 2%;position:relative;}
.content-container{background:#FFF;width:96%;margin-top:8px;padding:10px;position:relative;}
-->
</style>
</head>
<body>
<div id="header"><h1>Server Error</h1></div>
<div id="content">
<div class="content-container"><fieldset>
<h2>405 - HTTP verb used to access this page is not allowed.</h2>
<h3>The page you are looking for cannot be displayed because an invalid method (HTTP verb) was used to attempt access.</h3>
</fieldset></div>
</div>
</body>
Response headers:
allow: GET,HEAD,OPTIONS,TRACE
content-length: 1293
content-type: text/html
date: Wed,12 Oct 2022 17:15:02 GMT
server: Microsoft-IIS/10.0
x-powered-by: ASP.NET
But this is not affecting GET Request.
As I stated, it is a PUT Request.
How do I resolve it?
Often this error is caused by the WebDAV module that try to handle this kind of requests, an easy solution is to remove WebDAV from your system. You can easily get this done in "Turn Windows Features On or Off" simply un-ticking the checkbox.
If this solution does not solve your problem, you can try the solution in this link:
HTTP Error 405.0 when you visit a website that is hosted on a server that is running IIS.

Can I use NAudio to record audio in a Blazor app?

In a dotnetcore 3.0 Blazor app I want to be able to record audio using NAudio, instead of implementing an HTML5 control in Javascript. Does NAudio support this?
I have already tried the sample code below. I am getting a 0 byte wave file written to my Desktop.
#inject IJSRuntime JsRuntime
#using System
#using System.IO
#using NAudio.Wave
<button #ref="recordButton" #onclick="Record">Record</button>
<button #ref="stopRecording" #onclick="StopRecording">Stop</button>
#code {
ElementReference recordButton;
ElementReference stopRecording;
WaveInEvent waveIn;
public void Record()
{
var outputFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "NAudio");
Directory.CreateDirectory(outputFolder);
var outputFilePath = Path.Combine(outputFolder, "recorded.wav");
waveIn = new WaveInEvent();
WaveFileWriter writer = new WaveFileWriter(outputFilePath, waveIn.WaveFormat);
waveIn.StartRecording();
waveIn.DataAvailable += (s, a) =>
{
writer.Write(a.Buffer, 0, a.BytesRecorded);
};
}
public void StopRecording()
{
waveIn.StopRecording();
}
}
We had to use Javascript to access the user's microphone.

How to reproduce the Selenium Error - The HTTP request to the remote WebDriver timed out after 60 seconds

I am encountering the same error described in Selenium Error - The HTTP request to the remote WebDriver timed out after 60 seconds.
In order to better understand the problem, I need to create a minimal sample that reproduces the bug - an html page and a console app that uses Selenium to open it.
My question is: How exactly can I reproduce the bug, i.e. create an experimental program that intentionally triggers this bug?
Edit: In case it helps, according to IEDriver. Download. HTTP request to the remote WebDriver server timed out after 60 seconds:
The problem here is that when IE is in the process of downloading a file, the readyState of the browser never moves from interactive to complete
You could try to add a web page which includes a button control, in the button click event, you can call a web API to get data. In the web API method, add Thread. Sleep () method to stop the executing thread for a given amount of time (more than the request time). Then, if you trigger the button click event using Selenium WebDriver, it will show this error.
Code like this:
Code in mvc view:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script>
$(function () {
$("#buttonSearchPro").click(function () {
$.ajax({
url: "#Url.Action("GetData", "Home")",
async: false,
success: function (data) {
alert(data);
}
});;
});
});
</script>
<input type="button" id="buttonSearchPro" class="btn btnAction" value="Download" />
Code in MVC controller:
public ActionResult GetData()
{
Thread.Sleep(70000000);
return Json("OK", JsonRequestBehavior.AllowGet);
}
Code in console application:
private const string URL = #"http://localhost:65330/Home/Index";
private const string IE_DRIVER_PATH = #"D:\Downloads\webdriver\IEDriverServer_x64_3.14.0";
static void Main(string[] args)
{
//EdgeWebDriver();
InternetExplorerTest();
}
public static void InternetExplorerTest()
{
try{
var options = new InternetExplorerOptions()
{
InitialBrowserUrl = URL,
IntroduceInstabilityByIgnoringProtectedModeSettings = true
};
var driver = new InternetExplorerDriver(IE_DRIVER_PATH, options);
driver.Navigate();
//find the button and trigger click event.
driver.FindElementById("buttonSearchPro").Click() ;
driver.Close(); // closes browser
driver.Quit(); // closes IEDriverServer process
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine("OK");
Console.ReadKey();
}
the result like this:

How can I use iText to convert HTML with images and hyperlinks to PDF?

I'm trying to convert HTML to PDF using iTextSharp in an ASP.NET web application that uses both MVC, and web forms. The <img> and <a> elements have absolute and relative URLs, and some of the <img> elements are base64. Typical answers here at SO and Google search results use generic HTML to PDF code with XMLWorkerHelper that looks something like this:
using (var stringReader = new StringReader(xHtml))
{
using (Document document = new Document())
{
PdfWriter writer = PdfWriter.GetInstance(document, stream);
document.Open();
XMLWorkerHelper.GetInstance().ParseXHtml(
writer, document, stringReader
);
}
}
So with sample HTML like this:
<div>
<h3>HTML Works, but Broken in Converted PDF</h3>
<div>Relative local <img>: <img src='./../content/images/kuujinbo_320-30.gif' /></div>
<div>
Base64 <img>:
<img src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==' />
</div>
<div><a href='/somePage.html'>Relative local hyperlink, broken in PDF</a></div>
<div>
The resulting PDF: (1) is missing all images, and (2) all hyperlink(s) with relative URLs are broken and use a file URI scheme (file///XXX...) instead of pointing to the correct web site.
Some answers here at SO and others from Google search recommend replacing relative URLs with absolute URLs, which is perfectly acceptable for one-off cases. However, globally replacing all <img src> and <a href> attributes with a hard-coded string is unacceptable for this question, so please do not post an answer like that, because it will accordingly be downvoted.
Am looking for a solution that works for many different web applications residing in test, development, and production environments.
Out of the box XMLWorker only understands absolute URIs, so the described issues are expected behavior. The parser can't automagically deduce URI schemes or paths without some additional information.
Implementing an ILinkProvider fixes the broken hyperlink problem, and implementing an IImageProvider fixes the broken image problem. Since both implementations must perform URI resolution, that's the first step. The following helper class does that, and also tries to make web (ASP.NET) context calls (examples follow) as simple as possible:
// resolve URIs for LinkProvider & ImageProvider
public class UriHelper
{
/* IsLocal; when running in web context:
* [1] give LinkProvider http[s] scheme; see CreateBase(string baseUri)
* [2] give ImageProvider relative path starting with '/' - see:
* Join(string relativeUri)
*/
public bool IsLocal { get; set; }
public HttpContext HttpContext { get; private set; }
public Uri BaseUri { get; private set; }
public UriHelper(string baseUri) : this(baseUri, true) {}
public UriHelper(string baseUri, bool isLocal)
{
IsLocal = isLocal;
HttpContext = HttpContext.Current;
BaseUri = CreateBase(baseUri);
}
/* get URI for IImageProvider to instantiate iTextSharp.text.Image for
* each <img> element in the HTML.
*/
public string Combine(string relativeUri)
{
/* when running in a web context, the HTML is coming from a MVC view
* or web form, so convert the incoming URI to a **local** path
*/
if (HttpContext != null && !BaseUri.IsAbsoluteUri && IsLocal)
{
return HttpContext.Server.MapPath(
// Combine() checks directory traversal exploits
VirtualPathUtility.Combine(BaseUri.ToString(), relativeUri)
);
}
return BaseUri.Scheme == Uri.UriSchemeFile
? Path.Combine(BaseUri.LocalPath, relativeUri)
// for this example we're assuming URI.Scheme is http[s]
: new Uri(BaseUri, relativeUri).AbsoluteUri;
}
private Uri CreateBase(string baseUri)
{
if (HttpContext != null)
{ // running on a web server; need to update original value
var req = HttpContext.Request;
baseUri = IsLocal
// IImageProvider; absolute virtual path (starts with '/')
// used to convert to local file system path. see:
// Combine(string relativeUri)
? req.ApplicationPath
// ILinkProvider; absolute http[s] URI scheme
: req.Url.GetLeftPart(UriPartial.Authority)
+ HttpContext.Request.ApplicationPath;
}
Uri uri;
if (Uri.TryCreate(baseUri, UriKind.RelativeOrAbsolute, out uri)) return uri;
throw new InvalidOperationException("cannot create a valid BaseUri");
}
}
Implementing ILinkProvider is pretty simple now that UriHelper gives the base URI. We just need the correct URI scheme (file or http[s]):
// make hyperlinks with relative URLs absolute
public class LinkProvider : ILinkProvider
{
// rfc1738 - file URI scheme section 3.10
public const char SEPARATOR = '/';
public string BaseUrl { get; private set; }
public LinkProvider(UriHelper uriHelper)
{
var uri = uriHelper.BaseUri;
/* simplified implementation that only takes into account:
* Uri.UriSchemeFile || Uri.UriSchemeHttp || Uri.UriSchemeHttps
*/
BaseUrl = uri.Scheme == Uri.UriSchemeFile
// need trailing separator or file paths break
? uri.AbsoluteUri.TrimEnd(SEPARATOR) + SEPARATOR
// assumes Uri.UriSchemeHttp || Uri.UriSchemeHttps
: BaseUrl = uri.AbsoluteUri;
}
public string GetLinkRoot()
{
return BaseUrl;
}
}
IImageProvider only requires implementing a single method, Retrieve(string src), but Store(string src, Image img) is easy - note inline comments there and for GetImageRootPath():
// handle <img> elements in HTML
public class ImageProvider : IImageProvider
{
private UriHelper _uriHelper;
// see Store(string src, Image img)
private Dictionary<string, Image> _imageCache =
new Dictionary<string, Image>();
public virtual float ScalePercent { get; set; }
public virtual Regex Base64 { get; set; }
public ImageProvider(UriHelper uriHelper) : this(uriHelper, 67f) { }
// hard-coded based on general past experience ^^^
// but call the overload to supply your own
public ImageProvider(UriHelper uriHelper, float scalePercent)
{
_uriHelper = uriHelper;
ScalePercent = scalePercent;
Base64 = new Regex( // rfc2045, section 6.8 (alphabet/padding)
#"^data:image/[^;]+;base64,(?<data>[a-z0-9+/]+={0,2})$",
RegexOptions.Compiled | RegexOptions.IgnoreCase
);
}
public virtual Image ScaleImage(Image img)
{
img.ScalePercent(ScalePercent);
return img;
}
public virtual Image Retrieve(string src)
{
if (_imageCache.ContainsKey(src)) return _imageCache[src];
try
{
if (Regex.IsMatch(src, "^https?://", RegexOptions.IgnoreCase))
{
return ScaleImage(Image.GetInstance(src));
}
Match match;
if ((match = Base64.Match(src)).Length > 0)
{
return ScaleImage(Image.GetInstance(
Convert.FromBase64String(match.Groups["data"].Value)
));
}
var imgPath = _uriHelper.Combine(src);
return ScaleImage(Image.GetInstance(imgPath));
}
// not implemented to keep the SO answer (relatively) short
catch (BadElementException ex) { return null; }
catch (IOException ex) { return null; }
catch (Exception ex) { return null; }
}
/*
* always called after Retrieve(string src):
* [1] cache any duplicate <img> in the HTML source so the image bytes
* are only written to the PDF **once**, which reduces the
* resulting file size.
* [2] the cache can also **potentially** save network IO if you're
* running the parser in a loop, since Image.GetInstance() creates
* a WebRequest when an image resides on a remote server. couldn't
* find a CachePolicy in the source code
*/
public virtual void Store(string src, Image img)
{
if (!_imageCache.ContainsKey(src)) _imageCache.Add(src, img);
}
/* XMLWorker documentation for ImageProvider recommends implementing
* GetImageRootPath():
*
* http://demo.itextsupport.com/xmlworker/itextdoc/flatsite.html#itextdoc-menu-10
*
* but a quick run through the debugger never hits the breakpoint, so
* not sure if I'm missing something, or something has changed internally
* with XMLWorker....
*/
public virtual string GetImageRootPath() { return null; }
public virtual void Reset() { }
}
Based on the XML Worker documentation it's pretty straightforward to hook the implementations of ILinkProvider and IImageProvider above into a simple parser class:
/* a simple parser that uses XMLWorker and XMLParser to handle converting
* (most) images and hyperlinks internally
*/
public class SimpleParser
{
public virtual ILinkProvider LinkProvider { get; set; }
public virtual IImageProvider ImageProvider { get; set; }
public virtual HtmlPipelineContext HtmlPipelineContext { get; set; }
public virtual ITagProcessorFactory TagProcessorFactory { get; set; }
public virtual ICSSResolver CssResolver { get; set; }
/* overloads simplfied to keep SO answer (relatively) short. if needed
* set LinkProvider/ImageProvider after instantiating SimpleParser()
* to override the defaults (e.g. ImageProvider.ScalePercent)
*/
public SimpleParser() : this(null) { }
public SimpleParser(string baseUri)
{
LinkProvider = new LinkProvider(new UriHelper(baseUri, false));
ImageProvider = new ImageProvider(new UriHelper(baseUri, true));
HtmlPipelineContext = new HtmlPipelineContext(null);
// another story altogether, and not implemented for simplicity
TagProcessorFactory = Tags.GetHtmlTagProcessorFactory();
CssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true);
}
/*
* when sending XHR via any of the popular JavaScript frameworks,
* <img> tags are **NOT** always closed, which results in the
* infamous iTextSharp.tool.xml.exceptions.RuntimeWorkerException:
* 'Invalid nested tag a found, expected closing tag img.' a simple
* workaround.
*/
public virtual string SimpleAjaxImgFix(string xHtml)
{
return Regex.Replace(
xHtml,
"(?<image><img[^>]+)(?<=[^/])>",
new MatchEvaluator(match => match.Groups["image"].Value + " />"),
RegexOptions.IgnoreCase | RegexOptions.Multiline
);
}
public virtual void Parse(Stream stream, string xHtml)
{
xHtml = SimpleAjaxImgFix(xHtml);
using (var stringReader = new StringReader(xHtml))
{
using (Document document = new Document())
{
PdfWriter writer = PdfWriter.GetInstance(document, stream);
document.Open();
HtmlPipelineContext
.SetTagFactory(Tags.GetHtmlTagProcessorFactory())
.SetLinkProvider(LinkProvider)
.SetImageProvider(ImageProvider)
;
var pdfWriterPipeline = new PdfWriterPipeline(document, writer);
var htmlPipeline = new HtmlPipeline(HtmlPipelineContext, pdfWriterPipeline);
var cssResolverPipeline = new CssResolverPipeline(CssResolver, htmlPipeline);
XMLWorker worker = new XMLWorker(cssResolverPipeline, true);
XMLParser parser = new XMLParser(worker);
parser.Parse(stringReader);
}
}
}
}
As commented inline, SimpleAjaxImgFix(string xHtml) specifically handles XHR that may send unclosed <img> tags, which is valid HTML, but invalid XML that will break XMLWorker . A simple explanation & implementation of how to receive a PDF or other binary data with XHR and iTextSharp can be found here.
A Regex was used in SimpleAjaxImgFix(string xHtml) so that anyone using (copy/paste?) the code doesn't need to add another nuget package, but a HTML parser like HtmlAgilityPack should be used, since it's turns this:
<div><img src='a.gif'><br><hr></div>
into this:
<div><img src='a.gif' /><br /><hr /></div>
with only a few lines of code:
var hDocument = new HtmlDocument()
{
OptionWriteEmptyNodes = true,
OptionAutoCloseOnEnd = true
};
hDocument.LoadHtml("<div><img src='a.gif'><br><hr></div>");
var closedTags = hDocument.DocumentNode.WriteTo();
Also of note - use SimpleParser.Parse() above as a general blueprint to additionally implement a custom ICSSResolver or ITagProcessorFactory, which is explained in the documentation.
Now the issues described in the question should be taken care of. Called from a MVC Action Method:
[HttpPost] // some browsers have URL length limits
[ValidateInput(false)] // or throws HttpRequestValidationException
public ActionResult Index(string xHtml)
{
Response.ContentType = "application/pdf";
Response.AppendHeader(
"Content-Disposition", "attachment; filename=test.pdf"
);
var simpleParser = new SimpleParser();
simpleParser.Parse(Response.OutputStream, xHtml);
return new EmptyResult();
}
or from a Web Form that gets HTML from a server control:
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=test.pdf");
using (var stringWriter = new StringWriter())
{
using (var htmlWriter = new HtmlTextWriter(stringWriter))
{
ConvertControlToPdf.RenderControl(htmlWriter);
}
var simpleParser = new SimpleParser();
simpleParser.Parse(Response.OutputStream, stringWriter.ToString());
}
Response.End();
or a simple HTML file with hyperlinks and images on the file system:
<h1>HTML Page 00 on Local File System</h1>
<div>
<div>
Relative <img>: <img src='Images/alt-gravatar.png' />
</div>
<div>
Hyperlink to file system HTML page:
<a href='file-system-html-01.html'>Page 01</a>
</div>
</div>
or HTML from a remote web site:
<div>
<div>
<img width="200" alt="Wikipedia Logo"
src="portal/wikipedia.org/assets/img/Wikipedia-logo-v2.png">
</div>
<div lang="en">
English
</div>
<div lang="en">
iText
</div>
</div>
Above two HTML snippets run from a console app:
var filePaths = Path.Combine(basePath, "file-system-html-00.html");
var htmlFile = File.ReadAllText(filePaths);
var remoteUrl = Path.Combine(basePath, "wikipedia.html");
var htmlRemote = File.ReadAllText(remoteUrl);
var outputFile = Path.Combine(basePath, "filePaths.pdf");
var outputRemote = Path.Combine(basePath, "remoteUrl.pdf");
using (var stream = new FileStream(outputFile, FileMode.Create))
{
var simpleParser = new SimpleParser(basePath);
simpleParser.Parse(stream, htmlFile);
}
using (var stream = new FileStream(outputRemote, FileMode.Create))
{
var simpleParser = new SimpleParser("https://wikipedia.org");
simpleParser.Parse(stream, htmlRemote);
}
Quite a long answer, but taking a look at questions here at SO tagged html, pdf, and itextsharp, as of this writing (2016-02-23) there are 776 results against 4,063 total tagged itextsharp - that's 19%.
Very helpful post,
I was problem to render images in my report html to pdf. with your post I could do it.
I'm working with asp.mvc 5.
I only have to change this method of the ImageProviderClass
public virtual string GetImageRootPath() { return null; }
to
public virtual string GetImageRootPath() { HostingEnvironment.MapPath("~/Content/Images/") }
thanks!

jasper pdf report does not show up

my JSF 2.0 web application is intended to produce PDF reports.
the problem is that no PDF report is shown up in the explorer window.
I am using eclipse kepler, with apache-tomcat-7.0.52 and the version of jasper Ireport is 4.8
any help would be appreciated.
I will provide the whole java class :
package khldqr.beans;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
#ManagedBean
#SessionScoped
public class TestReport {
private List<Refugee> refugee;
public List<Refugee> connectRefugeeData() {
ResultSet rs = null;
PreparedStatement pst = null;
Connection con = Database.getConnection();
String stm = "Select R_NO, F_P_Name from M_MAIN_INFO where R_NO < 10";
refugee = new ArrayList<Refugee>();
try {
pst = con.prepareStatement(stm);
pst.execute();
rs = pst.getResultSet();
while (rs.next()) {
Refugee refugeelist = new Refugee();
refugeelist.setR_NO(rs.getInt(1));
refugeelist.setF_P_Name(rs.getString(2));
refugee.add(refugeelist);
}
} catch (SQLException e) {
e.printStackTrace();
}
return refugee;
}
public void PDF(ActionEvent actionEvent) throws IOException, JRException {
System.out.println("this is not my lucky day!!!!!");
File jasper = new File(FacesContext.getCurrentInstance().getExternalContext().getRealPath("report/Majd.jasper"));
byte[] bytes = JasperRunManager.runReportToPdf(jasper.getPath(),null,new JRBeanCollectionDataSource(refugee));
HttpServletResponse response =(HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
response.setContentType("application/pdf");
ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(bytes, 0 , bytes.length);
outputStream.flush();
outputStream.close();
FacesContext.getCurrentInstance().responseComplete();
}
public TestReport() {
connectRefugeeData();
}
public List<Refugee> getRefugee() {
return refugee;
}
public void setRefugee(List<Refugee> refugee) {
this.refugee = refugee;
}
}
and here is xhtml file:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Hello To GOPA World!!</title>
</h:head>
<h:body dir="rtl">
<h:form>
<p:commandButton value = "PDF" actionListener="#{testReport.PDF}"></p:commandButton>
</h:form>
<h:dataTable value="#{testReport.refugee}" var="var">
<h:column>
<h:outputText value="#{var.r_NO}"></h:outputText>
</h:column>
<h:column >
<h:outputText value="#{var.f_P_Name}"></h:outputText>
</h:column>
</h:dataTable>
</h:body>
</html>
I can see the message on the console and the page gets refreshed but no PDF report is come up the explorer screen
I have replaced the above PDF method with the code below, but in vain, the same result: no PDF report is coming up the explorer screen.
JasperPrint jasperPrint;
public void init() throws JRException{
JRBeanCollectionDataSource beanCollectionDataSource=new JRBeanCollectionDataSource(refugee);
String reportPath= "e:\\Rita.jasper";
jasperPrint=JasperFillManager.fillReport(reportPath, new HashMap(),beanCollectionDataSource);
}
public void PDF(ActionEvent actionEvent) throws JRException, IOException{
init();
HttpServletResponse httpServletResponse=(HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
// httpServletResponse.addHeader("Content-disposition", "attachment; filename=report.pdf");
FacesContext.getCurrentInstance().getExternalContext().setResponseContentType("‌​application/pdf");
ServletOutputStream servletOutputStream=httpServletResponse.getOutputStream();
JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);
System.out.println("All done the report is done");
servletOutputStream.flush();
servletOutputStream.close();
FacesContext.getCurrentInstance().responseComplete();
}
the code is correct, and there is nothing wrong with it.
the problem was some kind of security issue.
I faced the above problem when the report was in a full access folder to all users.
put when I put both of the requested xhtml and the report in a secured folder, everything went OK.
I don't know why!! but that was the case with me.
hoping others will make use of this.
thx.
<p:commandButton value = "PDF" actionListener="#{testReport.PDF}" ajax="false" type="submit"></p:commandButton>
you cant use ajax when calling jasperReports