I have a web app that displays a table the user can edit. In the process of editing, various inner HTML of the original table gets replaced with edits made by the user. Once the user is finished I would like to save the resulting table in a .html file so that I can include it in a PowerPoint slide without having to recreate it. Basically I want to capture the .aspx file as is after editing and write this to a file.
Any advice is appreciated.
Regards.
Basically I want to capture the .aspx file as is
Because you state "capture the ASPX", I'm assuming the data edits are persisted somewhere (memory/database). This means it is straightforward to override the Render() method of the control/page and redirect (or copy) the output stream to a file.
Example
protected override void Render( HtmlTextWriter writer ) {
using( HtmlTextWriter htmlwriter = new HtmlTextWriter( new StringWriter() ) ) {
base.Render( htmlwriter );
string renderedContent = htmlwriter.InnerWriter.ToString();
// do something here with the string, like save to disk
File.WriteAllText( #"c:\temp\foo.html", renderedContent );
// you could also Response.BinaryWrite() the data to the client
// so that it could be saved on the user's machine.
// and/or write it out to the output stream as well
writer.Write( renderedContent );
}
}
Sequence
User enters data
You store the results somewhere
You re-render the control with the most recent content
Capture the output of the control and write it out to a file
If you are doing it client side you can do something like this using jquery
http://jsfiddle.net/BAVzC/3/
You can then copy paste to a text file.
Just a few pointers.
You can get the whole inner html of a section of your page using jquery functions like html
You can use ajax to send this to your server.
You could write an http handler to receive this at the server. Since you only plan to save this to a fixed format html file, nothing else is required. I would not use a page to so as to avoid the extra overhead of creating all the controls, and a page will not receive html input unless you set ValidateRequest to "false".
Related
I have tried multiple plugins and c# classes to try and convert the HTML and CSS on my asp.net project to a pdf and even though the code used looks fine, and the button click works for other functions, I just cannot seem to get any html to pdf function to work. Has anyone else encountered this, or know if there is something I have missed to resolve it?
This is the latest code I have tried for hiqpdf in C#:
protected void Print_Button_Click(object sender, EventArgs e)
{
HtmlToPdf htmlToPdfConverter = new HtmlToPdf();
// set PDF page size, orientation and margins
htmlToPdfConverter.Document.PageSize = PdfPageSize.A4;
htmlToPdfConverter.Document.PageOrientation = PdfPageOrientation.Portrait;
htmlToPdfConverter.Document.Margins = new PdfMargins(0);
// convert HTML to PDF
htmlToPdfConverter.ConvertUrlToFile("http://localhost:51091/Printout","mcn.pdf");
}
It is not stated directly within theHiQpdf documentation of the method, but the method ConvertUrlToFile() stores the produced pdf file locally on the disc. On some example page (Convert URLs and HTML Code to PDF) the following comment can be found:
// ConvertUrlToFile() is called to convert the html document and save the resulted PDF into a file on disk
// Alternatively, ConvertUrlToMemory() can be called to save the resulted PDF in a buffer in memory
htmlToPdfConverter.ConvertUrlToFile(url, pdfFile);
Since your example shows a button-click eventhandler, the file is probably generated but not used to return in the http response. You have to write the data into the response. The methods ConvertToStream() or ConvertToMemory should come in handy to do so. Don't forget to use Response.Clear() or Response.ClearContent() and Response.ClearHeader() before that and Flush() and Close() afterwards.
I export data from my database to word in HTML format from my web application, which works fine for me , i have inserted image into record,
the document displays the image also , all works fine for me except when i save that file and send to someone else .. ms word will not find link to that image
Is there anyway to save that image on the document so path issues will not raise
Here is my code : StrTitle contains all the HTML including Image links as well
string strBody = "<html>" +
"<body>" + strTitle +
"</body>" +
"</html>";
string fileName = "Policies.doc";
//object missing = System.Reflection.Missing.Value;
// You can add whatever you want to add as the HTML and it will be generated as Ms Word docs
Response.AppendHeader("Content-Type", "application/msword");
Response.AppendHeader("Content-disposition", "attachment; filename=" + fileName);
Response.Write(strBody);
You can create your html img tag with the image data encoded with base64. This way the image data is contained in the html document it self.
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA..." />
You images are probably only available via filesystem (i.e. their src starts with file).
There are a few ways
Make the image available via the internet: make sure their src starts with http and that they are hosted on a web server visible to the downloader (for example, the same server from which they are dowonloading the image)
Use a library, for example see NuGet
You can inline the images as #DevZer0 suggests.
Based on experience
Is the simplest to implement but has some annoyances (the server needs to be available to the user)
Is probably the best way if you do a lot of Word or Office files manipulation.
Can be done and it would solve the problem, although you wouldn't have a full library to support further use cases.
Use a word document creation library if you really want to have flexibility in creating doc or docx type files. Like all other popular document formats, the structure needs to be accurate enough for the program that opens up the documents. Like you obviously cannot create a PDF file just by setting content type "application/PDF", if your content is not in a structure that PDF reader expects. Content type would just make the browser identify the extension (incorrectly in this case) and download it as a PDF, but its actually simple text. Same goes for MS word or any other format that requires a particular document structure to be parsed and displyed properly.
Since every picture, table is of type shape in Word/Excel/Powerpoint, you could simply add with your program an AlternativeText to your picture, which would actually save a URL of the download URL and when you open, it will retrieve its URL and replace it.
foreach (NetOffice.WordApi.InlineShape s in docWord.InlineShapes)
{
if (s.Type==NetOffice.WordApi.Enums.WdInlineShapeType.wdInlineShapePicture && s.AlternativeText.Contains("|"))
{
s.AlternativeText=<your website URL to download the picture>;
}
}
This would be the C# approach, but would require more time for the picture. If you write a small software for it, which replaces all pictures which contain a s.AlternativeText, you could replace a lot of pictures at same time.
NetOffice.WordApi.InlineShape i=appWord.ActiveDocument.InlineShapes.AddPicture(s.AlternativeText, false, true);
It will look for the picture at that location.
You can do that for your whole document with the 1 loop I wrote you. Means, if it is a picture and contains some AlternativeText, then inside you loop you use the AddPicture function.
Edit: Anoter solution, would be to set a hyperlink to your picture, which would actually go to a FTP server where the picture is located and when you click on the picture, it will open it, means he can replace it by himself(bad, if you have 200 pictures in your document)
Edit according Clipboard:
string html = Clipboard.GetText(TextDataFormat.Html);
File.WriteAllText(temporaryFilePath, html);
NetOffice.WordApi.InlineShape i=appWord.ActiveDocument.InlineShapes.AddPicture(temporaryFilePath, false, true);
The Clipboard in Word is capable to transform a given HTML and when you paste it to transform that table or picture into Word. This works too for Excel, but doesn't for Powerpoint. You could do something like that for your pictures and drag and drop from your database.
There are so many good tutorials out there about inserting an image inside a table in a database, using the FileUpload controller.
Yet I cannot find a good tutorial about how to fetch these images and display them.
When I used to store the image name or path in the database (as a Varchar), It would be very simple by doing something like this...
HTML/ASP:
<img src="" runat="server" id="myImage" />
C#:
myImage.Src = myReader.getValue(0).toString();
The Result:
<img src="/Images/pic.png" runat="server" id="myImage" />
And Voila, the picture will be displayed.
But Now I would like to fetch uploaded images, not a path, means the type of the table column is IMAGE.
Some tutorials will eventually lead to display a picture in FULL SCREEN.
I do not want that, I simply want to fetch and display the image the same way it is displayed in the previous example, with a given size and place inside my web page.
Why am I uploading images to the database? Because these images are "Profile Pictures", not public pictures, I do not want a guest to simply browse for /Images/ to find all the pictures of my web site, public and private.
First of all, to do what you want, I would just copy the file to a temporary location and use that location for the "src" attribute. Later, you could delete the file. The much more complicated way is to create an aspx page that writes the image to the webpage as a binary stream. This page would grab the image from the database and just write the stream out in the response. You would then use this aspx page in the src attribute of your image. However, storing the image path in the database and actual file on the file system doesn't mean that the folder has to be browse-able or public. You can turn directory browsing off for example.
Create a custom IHttpHandler implementation that can serve your images from your database. You could, for example, get the bytes into a stream and copy that stream to the output of the web response.
Here is a simple example:
public class MyImageHandler : IHttpHandler
{
public bool IsReusable { get { return true; } }
public void ProcessRequest(HttpContext ctx)
{
Stream yourStream = ...; // This is where you get your data from your database
ctx.Response.ContentType = "image/jpeg";
yourStream.CopyTo(ctx.Response.OutputStream);
}
}
Then you need to configure it to respond to the URLs you wish.
You could either use the Web.config file to do this
Or create an .ashx file and have it point to your own HTTP handler
If you have any questions about it, just write a comment.
You will need an aspx page reading the image from the database and returning the raw bytes.
Here's a quick sketch how to do this:
byte[] data = (byte[])myReader.getValue(0);
Response.ContentType = "image/jpeg"; //or whatever your used image type is
Response.OutputStream.Write(data, 0, data.Length);
Response.End();
An alternative would be to implement a custom HttpHandler for this.
The other part is "calling" this page from your img tags with a parameter specifying the image id:
myImage.Src = "/image.aspx?id=" + myReader.getValue(0).toString();
I looking for the easiest way to export the currently viewed asp.net web page to a PDF document using iTextSharp - it can be either a screenshot of it or passing in the url to generate the document. Sample code would be greatly appreciated. Many thanks in advance!
On a past project, we used Supergoo ABCPDF
to do something like you need to and it worked quite well. You basicly feed it an url and it process the HTML page into a PDF.
On the downside, it's a licensed software with costs associated to it and we had some performance issues when exporting a lot of large PDF at the same time.
Hope this helps !
Adding to what Darin said in his comment.
You can try using wkhtmltopdf to generate PDF files. It takes URL as input. This is what I have used for my SO application so2pdf.
It is not that easy (or i think so), i had same problem and i had to write code to generate exact page in pdf. It depends of page and used styles etc. So i create drawing of each element.
For some project i used Winnovative HTML to PDF converter but it is not free.
Give a try with PDFSharp (to generate PDF files at runtime), and it's Open Source library :
http://pdfsharp.com/PDFsharp/index.php?option=com_content&task=view&id=27&Itemid=1
Alternative solution : http://www.bratched.com/en/component/content/article/76-how-to-convert-xhtml-to-pdf-in-c.html
There is an example Convert the Current HTML Page to PDF on WInnovative website which does exactly this. The relevant C# code to convert the currently viewed asp.net web page to a PDF document is:
// Controls if the current HTML page will be rendered to PDF or as a normal page
bool convertToPdf = false;
protected void convertToPdfButton_Click(object sender, EventArgs e)
{
// The current ASP.NET page will be rendered to PDF when its Render method will be called by framework
convertToPdf = true;
}
protected override void Render(HtmlTextWriter writer)
{
if (convertToPdf)
{
// Get the current page HTML string by rendering into a TextWriter object
TextWriter outTextWriter = new StringWriter();
HtmlTextWriter outHtmlTextWriter = new HtmlTextWriter(outTextWriter);
base.Render(outHtmlTextWriter);
// Obtain the current page HTML string
string currentPageHtmlString = outTextWriter.ToString();
// Create a HTML to PDF converter object with default settings
HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter();
// Set license key received after purchase to use the converter in licensed mode
// Leave it not set to use the converter in demo mode
htmlToPdfConverter.LicenseKey = "fvDh8eDx4fHg4P/h8eLg/+Dj/+jo6Og=";
// Use the current page URL as base URL
string baseUrl = HttpContext.Current.Request.Url.AbsoluteUri;
// Convert the current page HTML string a PDF document in a memory buffer
byte[] outPdfBuffer = htmlToPdfConverter.ConvertHtml(currentPageHtmlString, baseUrl);
// Send the PDF as response to browser
// Set response content type
Response.AddHeader("Content-Type", "application/pdf");
// Instruct the browser to open the PDF file as an attachment or inline
Response.AddHeader("Content-Disposition", String.Format("attachment; filename=Convert_Current_Page.pdf; size={0}", outPdfBuffer.Length.ToString()));
// Write the PDF document buffer to HTTP response
Response.BinaryWrite(outPdfBuffer);
// End the HTTP response and stop the current page processing
Response.End();
}
else
{
base.Render(writer);
}
}
how do external counter track unique visitors via image
i'd also like to get Referrer if possible.
something like img="http://www.somecounterdomain.com/count.php?page=83599"
i'm using ASP.NET, c#
i'm aware of a user can "cheat" but would like to make that posibility minimal.
additional difficulty is that i should trach external server and can't implement c# code there.
what i can is only imlement a counter imag or smth like that.
i try to use generated image.
thx for answers.
Basically what you need to do is the following.
1- Create either a .ashx or .aspx. Assuming you go with .aspx and call it StatServer.aspx, the Page_Load function will read the query string and write the data to a database, you will see the querystring in step 2. If you want, you can return a image which can be rendered. Some rough code will look something like this.
private void Page_Load(object sender, EventArgs e)
{
WriteQueryStringInformationToDB(Request.QueryString);
Image image = LoadYourImageHere();
using (MemoryStream stream = new MemoryStream())
{
base.Response.Clear();
base.Response.ContentType = "image/png";
image.Save(stream, ImageFormat.Png);
stream.WriteTo(base.Response.OutputStream);
base.Response.End();
}
}
2- This is the magic, you create a small .js file. In this file you have a function lets call it mystats() which will essentially gather the client side information and make a call to the URL hosting the page you created in step 1. The client side information like screen size, referer etc. is all passed on the querystring. One important thing to include in the function is an ID which indicates which which counter you are updating, that way you can use your counter on multiple sites. A very simple .js might look something like this. (Note tested etc... :))
function mystats(id)
{
// Base URL including the ID of the counter
var url="http://yourdomainorservername/statserver.aspx?id="+id;
// Add the referer to the url querystring
url += "&r=" + escape(document.referrer);
// Add screen width + height
url += "&w=" + screen.width + "&h=" + screen.height;
document.write('<img src="'+url+'" border=0 alt="Site statistics">');
}
3- On the web pages that you want to apply the counter, you add a script block that includes the the .js file from your server and calls the mystats function from an img tag, this causes the js code to collect the info and send a request to your server, which in turn updates the DB and returns the image stream to display.
Getting the 'referer' is easy and for counting unique visitors you'll need to set/check for cookies.