I'm dynamically creating an HTML file using HTMLTEXTWRITER, I can view it in browsers but when I try to view this html in an iframe, nothing is displayed! what is wrong what dynamically generated htmls? also iframe doesn't display some HTMLs in firefox, here is how I create my html:
static string GetDivElements()
{
// Initialize StringWriter instance.
StringWriter stringWriter = new StringWriter();
// Put HtmlTextWriter in using block because it needs to call Dispose.
using (HtmlTextWriter writer = new HtmlTextWriter(stringWriter))
{
// Loop over some strings.
foreach (var word in _words)
{
// Some strings for the attributes.
string classValue = "ClassName";
string urlValue = "http://www.dotnetperls.com/";
string imageValue = "image.jpg";
// The important part:
writer.AddAttribute(HtmlTextWriterAttribute.Class, classValue);
writer.RenderBeginTag(HtmlTextWriterTag.Div); // Begin #1
...my html
writer.RenderBeginTag(HtmlTextWriterTag.Img); // Begin #3
writer.RenderEndTag(); // End #3
writer.Write(word);
writer.RenderEndTag(); // End #2
writer.RenderEndTag(); // End #1
}
}
// Return the result.
string pre = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">";
pre += "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head>";
pre += "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\"><title></title></head><body>";
return stringWriter.ToString();// +"</body></html>";
}
private void Form1_Load(object sender, EventArgs e)
{
using (StreamWriter outfile =
new StreamWriter(#"d:\myFile.htm"))
{
outfile.Write(GetDivElements());
}
}
Related
I want to convert the raw html code to pdf file.
This is my Controller code
#RequestMapping("getpdf")
public void doGet(HttpServletRequest request,
HttpServletResponse response,String ref){
OutputStream out = null;
Document document = new Document(PageSize.A4, 50, 50, 50, 50);
java.util.List items = null;
ArticalBean abean=serviceLayer.getArtical(Integer.parseInt(ref));
items = new ArrayList();
items.add(abean.getArticle());
try {
response.setContentType("application/pdf");
PdfWriter.getInstance(document, response.getOutputStream());
document.open();
Paragraph paragraph = new Paragraph("Microweb Systems");
document.add(paragraph);
ListItem listItem;
com.lowagie.text.List list = new com.lowagie.text.List(true, 15);
Iterator i = items.iterator();
while(i.hasNext()) {
listItem = new ListItem((String)i.next(),
FontFactory.getFont(FontFactory.TIMES_ROMAN, 12));
list.add(listItem);
}
document.add(list);
} catch (Exception e) {
} finally {
document.close();
}
document.close();
}
It converts the HTML codes to PDF but that pdf also contains the tags
Like
<h1>Hello World</h1>
Is there is any way to remove these tags and show only Data.
I am providing the data from database via DTO.
If I understand your question, you want to remove the tags.
This can be done with String.replaceAll(String regex, String replacement).
For example myString.replaceAll("^<[.]*>$" , ""); would remove any tags.
This, however, does not make the pdf look like the page does in a browser.
I have tried this code
public System.Drawing.Bitmap CaptureWebPage(string URL)
{
// create a hidden web browser, which will navigate to the page
System.Windows.Forms.WebBrowser web = new System.Windows.Forms.WebBrowser();
// we don't want scrollbars on our image
web.ScrollBarsEnabled = false;
// don't let any errors shine through
web.ScriptErrorsSuppressed = true;
// let's load up that page!
web.Navigate(URL);
// wait until the page is fully loaded
while (web.ReadyState != WebBrowserReadyState.Complete)
System.Windows.Forms.Application.DoEvents();
System.Threading.Thread.Sleep(1500); // allow time for page scripts to update
// the appearance of the page
// set the size of our web browser to be the same size as the page
int width = web.Document.Body.ScrollRectangle.Width;
int height = web.Document.Body.ScrollRectangle.Height;
web.Width = width;
web.Height = height;
// a bitmap that we will draw to
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(width, height);
// draw the web browser to the bitmap
web.DrawToBitmap(bmp, new System.Drawing.Rectangle(0, 0, width, height));
return bmp; // return the bitmap for processing
}
protected void btnConvert_Click(object sender, EventArgs e)
{
Bitmap bitmap = new Bitmap(CaptureWebPage(txtUrl.Text));
Response.ContentType = "image/jpeg";
bitmap.Save(Response.OutputStream, ImageFormat.Jpeg);
bitmap.Dispose();
bitmap.Dispose();
Response.End();
}
I am able to capture google.com,but not able to capture images of our web site since it contains form authentication so it redirects me to login page and login page is captured.Please help to pass through authentication.Can we use sessions,cookies or anything with the WebBrowser to valid it Or something.Please suggest.
Try on the intended page on your website :
System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.IO.StringWriter sw = new System.IO.StringWriter(sb);
Page.RenderControl(new HtmlTextWriter(sw));
and then use the HTML in the string builder to render the page like the example below (Reference : Convert HTML string to image) :
using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
class Program
{
static void Main(string[] args)
{
var source = #"
<!DOCTYPE html>
<html>
<body>
<p>An image from W3Schools:</p>
<img
src=""http://www.w3schools.com/images/w3schools_green.jpg""
alt=""W3Schools.com""
width=""104""
height=""142"">
</body>
</html>";
StartBrowser(source);
Console.ReadLine();
}
private static void StartBrowser(string source)
{
var th = new Thread(() =>
{
var webBrowser = new WebBrowser();
webBrowser.ScrollBarsEnabled = false;
webBrowser.DocumentCompleted +=
webBrowser_DocumentCompleted;
webBrowser.DocumentText = source;
Application.Run();
});
th.SetApartmentState(ApartmentState.STA);
th.Start();
}
static void
webBrowser_DocumentCompleted(
object sender,
WebBrowserDocumentCompletedEventArgs e)
{
var webBrowser = (WebBrowser)sender;
using (Bitmap bitmap =
new Bitmap(
webBrowser.Width,
webBrowser.Height))
{
webBrowser
.DrawToBitmap(
bitmap,
new System.Drawing
.Rectangle(0, 0, bitmap.Width, bitmap.Height));
bitmap.Save(#"filename.jpg",
System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}
What is the best way to generate html page from data in view? I have a html template with all tables and etc. Don't want to use any templating like JqueryTemplate.
Try this approach using the hiqpdf html to pdf converter, a commercial product:
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
Session["MySessionVariable"] = "My Session Variable Value assigned in Index";
return View();
}
public ActionResult About()
{
return View();
}
public string RenderViewAsString(string viewName, object model)
{
// create a string writer to receive the HTML code
StringWriter stringWriter = new StringWriter();
// get the view to render
ViewEngineResult viewResult = ViewEngines.Engines.FindView(ControllerContext, viewName, null);
// create a context to render a view based on a model
ViewContext viewContext = new ViewContext(
ControllerContext,
viewResult.View,
new ViewDataDictionary(model),
new TempDataDictionary(),
stringWriter
);
// render the view to a HTML code
viewResult.View.Render(viewContext, stringWriter);
// return the HTML code
return stringWriter.ToString();
}
[HttpPost]
public ActionResult ConvertThisPageToPdf()
{
// get the HTML code of this view
string htmlToConvert = RenderViewAsString("Index", null);
// the base URL to resolve relative images and css
String thisPageUrl = this.ControllerContext.HttpContext.Request.Url.AbsoluteUri;
String baseUrl = thisPageUrl.Substring(0, thisPageUrl.Length - "Home/ConvertThisPageToPdf".Length);
// instantiate the HiQPdf HTML to PDF converter
HtmlToPdf htmlToPdfConverter = new HtmlToPdf();
// hide the button in the created PDF
htmlToPdfConverter.HiddenHtmlElements = new string[] { "#convertThisPageButtonDiv" };
// render the HTML code as PDF in memory
byte[] pdfBuffer = htmlToPdfConverter.ConvertHtmlToMemory(htmlToConvert, baseUrl);
// send the PDF file to browser
FileResult fileResult = new FileContentResult(pdfBuffer, "application/pdf");
fileResult.FileDownloadName = "ThisMvcViewToPdf.pdf";
return fileResult;
}
[HttpPost]
public ActionResult ConvertAboutPageToPdf()
{
// get the About view HTML code
string htmlToConvert = RenderViewAsString("About", null);
// the base URL to resolve relative images and css
String thisPageUrl = this.ControllerContext.HttpContext.Request.Url.AbsoluteUri;
String baseUrl = thisPageUrl.Substring(0, thisPageUrl.Length - "Home/ConvertAboutPageToPdf".Length);
// instantiate the HiQPdf HTML to PDF converter
HtmlToPdf htmlToPdfConverter = new HtmlToPdf();
// render the HTML code as PDF in memory
byte[] pdfBuffer = htmlToPdfConverter.ConvertHtmlToMemory(htmlToConvert, baseUrl);
// send the PDF file to browser
FileResult fileResult = new FileContentResult(pdfBuffer, "application/pdf");
fileResult.FileDownloadName = "AboutMvcViewToPdf.pdf";
return fileResult;
}
}
Source of this sample code: How to convert HTML to PDF using HiQPDF
Just create pdf server side and return File instead of html view.
I don't what kind of pdf provider do you use but this a solution for iTextSharp:
How to return PDF to browser in MVC?
I'm using the following to convert HTML to PDF:
InputStream convert(InputStream fileInputStream) {
PipedInputStream inputStream = new PipedInputStream()
PipedOutputStream outputStream = new PipedOutputStream(inputStream)
new Thread({
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(false);
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(fileInputStream)
ITextRenderer renderer = new ITextRenderer()
renderer.setDocument(document, "")
renderer.layout()
renderer.createPDF(outputStream)
}).start()
return inputStream
}
From the documentation, apparently I should be able to set a "User Agent" resolver somewhere, but I'm not sure where, exactly. Anyone know how to ignore external CSS in a document?
Not the same question but my answer for that one will work here too: Resolving protected resources with Flying Saucer (ITextRenderer)
Override this method:
public CSSResource getCSSResource(String uri) {
return new CSSResource(resolveAndOpenStream(uri));
}
with
public CSSResource getCSSResource(String uri) {
return new CSSResource(new ByteArrayInputStream([] as byte[]));
}
I have embedded the signed applet in following html page,
<input type="hidden" name="xmldata" id="xmldata" value=""/>
<APPLET CODE="com.syntel.upload.readFileApplet.class" ARCHIVE="sign-upload.jar" HEIGHT="200" WIDTH="475" ALIGN="bottom">
This browser does not appear to support Applets.
</APPLET>
Following readFileApplet class read the xml file from client filesystem ,
public class readFileApplet extends Applet {
StringBuffer strBuff;
public void init() {
add(txtArea, "center");
readFile();
String xmldata = strBuff.toString();
//TODO: set the xmldata string to html hidden variable
}
public void readFile() {
String line;
try {
InputStream in = new FileInputStream("c:\\ftlmb\\finstmt.xml");
BufferedReader bf = new BufferedReader(new InputStreamReader(in));
strBuff = new StringBuffer();
while ((line = bf.readLine()) != null) {
strBuff.append(line + "\n");
}
} catch (IOException e) {
txtArea.append(e.getMessage());
}
}
}
I am able to read the xml using applet but unable to set the xmldata string to hidden variable "xmldata" which is in html page.
Is there any API which i can use to get the DOM so that i can set the value to hidden variable.
Please help me out to solve this problem.
com.sun.java.browser.dom.DOMService
See http://www.javaworld.com/javaworld/jw-06-2005/jw-0627-plugin.html?page=3