I am writing a service on the local server side which will accept the printer name and other inputs from the UI application and print the html file to the desired network printer. it is not a desktop application. I have a processed html file which I am reading into a string and want its output sent to the desired printer.
1 way I could found is to create an image by reading it into a JEditorPane(though using a swing class is not great approach) and then saving an image which is then sent to the printer. But it fails when the html has an tag and that image is not renderred within the image created by html. Can someone help me with a method that can solve my problem. The printer is able to support postscripts as well.
This is my approach
protected void generateDoc(DataObj data) {
DocFlavor dsc =
DocFlavor.INPUT_STREAM.PNG;
// get the html file's contents
String receipt =
getFileContents("Receipt.html");
// process the html contents and insert the data details
receipt = processHTMLContents(receipt, data);
// create image of the receipt
createReceiptImage(receipt);
InputStream is =
null;
try {
is =
new FileInputStream(new File("testingToday.png")); // the same image which was created below
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// create the doc to be sent to the printer
Doc doc =
new SimpleDoc(is, dsc, null);
return doc;
}
/**
* Create an image of the html receipt.
* #param htmlReceipt processed html receipt
* #return
* #throws InterruptedException
*/
protected void createReceiptImage(String htmlReceipt) throws InterruptedException {
JEditorPane pane =
new JEditorPane();
//pane.setEditable(false);
pane.setEditorKit(new HTMLEditorKit());
pane.setContentType("text/html");
pane.setText(htmlReceipt);
pane.setSize(650, 850);
pane.setBackground(Color.white);
// Create a BufferedImage
BufferedImage image =
new BufferedImage(pane.getWidth(), pane.getHeight(),
BufferedImage.TYPE_INT_ARGB);
Graphics2D g =
image.createGraphics();
// Have the image painted by SwingUtilities
JPanel container =
new JPanel();
SwingUtilities.paintComponent(g, pane, container, 0, 0, image
.getWidth(), image.getHeight());
g.dispose();
ImageIO.write(image, "PNG", new File("testingToday.png")); // this would be replaced by a relative network location
}
and this doc is then sent to the printer. but this is not a desirable approach as it is swing class and it is not able to render any images inside the html. I have already spent around a week over it but still cant end upon a solution. how to fix this or what can be the solution?
Although the question seems old, you can have a look at this question.. Basically it converts a HTML to PDF & then you print the PDF... hope this helps
Related
I have an sql statements that selects a table of data that i want to export to excel in the .xls format,
i added this table to a grid view then rendered that grid view to create an html writer and write it on excel file using asp.net.
But i keep having this warning that the file format and extension does not match.
The issue is that the file you are creating is not a genuine Excel file. It's HTML with a .xls extension.
Please, i need to know what is the best way to export these selected data to the xls file without the warning.
I Have also tried exporting from the dataTable directly, but i still get the warning when tying to open the excel.
// these namespaces need to be added to your code behind file
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
namespace MySpot.UserPages
{
public partial class Journal : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MySpotDBConnStr"].ConnectionString);
DataTable dt = new DataTable();
// regular page_load from .aspx file
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
}
// added a button with ID=btnDownload and double clicked it's onclick event to auto create method
protected void btnDownload_Click(object sender, EventArgs e)
{
string queryStr = "SELECT * from table";
SqlDataAdapter sda = new SqlDataAdapter(queryStr, conn);
sda.Fill(dt);
ExportTableData(dt);
}
// this does all the work to export to excel
public void ExportTableData(DataTable dtdata)
{
string attach = "attachment;filename=journal.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attach);
Response.ContentType = "application/ms-excel";
if (dtdata != null)
{
foreach (DataColumn dc in dtdata.Columns)
{
Response.Write(dc.ColumnName + "\t");
//sep = ";";
}
Response.Write(System.Environment.NewLine);
foreach (DataRow dr in dtdata.Rows)
{
for (int i = 0; i < dtdata.Columns.Count; i++)
{
Response.Write(dr[i].ToString() + "\t");
}
Response.Write("\n");
}
Response.End();
}
}
}
}
http://blogs.msdn.com/b/vsofficedeveloper/archive/2008/03/11/excel-2007-extension-warning.aspx
The current design does not allow you to open HTML content from a web site in Excel unless the extension of the URL is .HTM/.HTML/.MHT/.MHTML. So ASP pages that return HTML and set the MIME type to something like XLS to try to force the HTML to open in Excel instead of the web browser (as expected) will always get the security alert since the content does not match the MIME type. If you use an HTML MIME type, then the web browser will open the content instead of Excel. So there is no good workaround for this case because of the lack of a special MIME type for HTML/MHTML that is Excel specific. You can add your own MIME type if you control both the web server and the client desktops that need access to it, but otherwise the best option is to use a different file format or alert your users of the warning and tell them to select Yes to the dialog.
I'm looking for a free tool or dlls that I can use to write my own code in .NET to process some web requests.
Let's say I have a URL with some query string parameters similar to http://www.example.com?param=1 and when I use it in a browser several redirects occur and eventually HTML is rendered that has a frameset and a frame's inner html contains a table with data that I need. I want to store this data in the external file in a CSV format. Obviously the data is different depending on the querystring parameter param. Let's say I want to run the application and generate 1000 CSV files for param values from 1 to 1000.
I have good knowledge in .NET, javascript, HTML, but the main problem is how to get the final HTML in the server code.
What I tried is I created a new Form Application, added a webbrowser control and used code like this:
private void FormMain_Shown(object sender, EventArgs e)
{
var param = 1; //test
var url = string.Format(Constants.URL_PATTERN, param);
WebBrowserMain.Navigated += WebBrowserMain_Navigated;
WebBrowserMain.Navigate(url);
}
void WebBrowserMain_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
if (e.Url.OriginalString == Constants.FINAL_URL)
{
var document = WebBrowserMain.Document.Window.Frames[0].Document;
}
}
But unfortunately I receieve unauthorizedaccessexception because probably frame and the document are in different domains. Does anybody has an idea of how to work around this and maybe another brand new approach to implement functionality like this?
Thanks to the Noseratio's comments I managed to do that with the WebBrowser control. Here are some major points that might help others who have similar questions:
1) DocumentCompleted event should be used. For Navigated event body of the document is NULL.
2) Following answer helped a lot: WebBrowserControl: UnauthorizedAccessException when accessing property of a Frame
3) I was not aware about IHTMLWindow2 similar interfaces, for them to work correctly I added references to following COM libs: Microsoft Internet Controls (SHDocVw), Microsoft HTML Object Library (MSHTML).
4) I grabbed the html of the frame with the following code:
void WebBrowserMain_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (e.Url.OriginalString == Constants.FINAL_URL)
{
try
{
var doc = (IHTMLDocument2) WebBrowserMain.Document.DomDocument;
var frame = (IHTMLWindow2) doc.frames.item(0);
var document = CrossFrameIE.GetDocumentFromWindow(frame);
var html = document.body.outerHTML;
var dataParser = new DataParser(html);
//my logic here
}
5) For the work with Html, I used the fine HTML Agility Pack that has some pretty good XPath search.
I'm showing a PDF in an <iframe> as follows:
<iframe src="/itextPdfServlet" height="600px" width="700px"></iframe>
I would like to disable the print option for this. How can I achieve this?
my servlet
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String fullPath = (String) request.getSession().getAttribute("fullPath");
response.setContentType("application/pdf");
ServletOutputStream out = null;
try{
File file = new File( fullPath );
FileInputStream fileIn = new FileInputStream( file );
out = response.getOutputStream();
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document, out);
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfReader reader = new PdfReader(fileIn);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("fullPath"));
stamper.setEncryption("reader_password".getBytes(), "permission_password".getBytes(),
~(PdfWriter.ALLOW_COPY | PdfWriter.ALLOW_PRINTING ), PdfWriter.STANDARD_ENCRYPTION_128);
stamper.close();
PdfImportedPage page = writer.getImportedPage(reader, 1);
document.newPage();
cb.addTemplate(page, 0, 0);
document.add(new Paragraph("my timestamp"));
response.setHeader("Expires", "0");
response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma", "public");
document.close();
}catch(Exception e){
}
}
Treating visitors or customers like enemies might not be in your best interest. You can disable printing in the options of a PDF file when generating the file:
PdfReader reader = new PdfReader("testpdf.pdf");
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("my-pdf-file.pdf"));
stamper.setEncryption("reader_password".getBytes(), "permission_password".getBytes(), ~(PdfWriter.ALLOW_COPY | PdfWriter.ALLOW_PRINTING ), PdfWriter.STANDARD_ENCRYPTION_128);
stamper.close();
But I know at least one PDF viewer which doesn't care about these options. I know a lot of tools that can make screenshots, so even if your PDF makes me angry, I just print the screenshot. There are screen automation tools that will even page through the file for me, make a screenshot for every page and a little script will compile a new PDF from that.
You can also try to disable printing with JavaScript in the web browser. That would then force me to install a tool like Tampermonkey or similar that kicks your script out of my browser.
Usually, a much better approach is to put watermarks in the PDF file which say who downloaded / bought the file and then harass them, if the PDF file leaks out. That way, you're not annoying everyone.
That said, consider how much your PDFs are worth and how much suing someone would cost (money and negative feedback wise). Most of the time, investing your money in great service will earn you much more money than you can lose by people printing PDFs (they would also have to do something with those prints before it could have any impact on your revenue, rights, ...)
I have never worked with iText, but I assume this might help you a little:
iText Java disable print pdf
I have a process where the html is stored in database with image links. the images are also stored in db as well. I've created a controller action which reads the image from database. the path I'm generating is something like /File/Image?path=Root/test.jpg.
this image path is embedded in html in img tag like <img alt="logo" src="/File/Image?path=Root/001.jpg" />
I'm trying to use itextsharp to read the html from the database and create a pdf document
string _html = GenerateDocumentHelpers.CommissioningSheet(fleetId);
string _html = GenerateDocumentHelpers.CommissioningSheet(fleetId);
Document _document = new Document(PageSize.A4, 80, 50, 30, 65);
MemoryStream _memStream = new MemoryStream();
PdfWriter _writer = PdfWriter.GetInstance(_document, _memStream);
StringReader _reader = new StringReader(_html);
HTMLWorker _worker = new HTMLWorker(_document);
_document.Open();
_worker.Parse(_reader);
_document.Close();
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=Commissioning.pdf");
Response.ContentType = "application/pdf";
Response.Buffer = true;
Response.OutputStream.Write(_memStream.GetBuffer(), 0, _memStream.GetBuffer().Length);
Response.OutputStream.Flush();
Response.End();
return new FileStreamResult(Response.OutputStream, "application/pdf");
This code gives me an illegal character error. this comes from the image tag, it is not recognizing ? and = characters, is there a way I can render this html with img tag so that when I create a pdf it renders the html and image from the database and creates a pdf or if itextsharp can't do it, can you provide me with any other third party open source tools that can accomplish this task?
If the image source isn't a fully qualified URL including protocol then iTextSharp assumes that it is a file-based URL. The solution is to just convert all image links to absolute in the form http://YOUR_DOMAIN/File/Image?path=Root/001.jpg.
You can also set a global property on the parser that works pretty much the same as the HTML <BASE> tag:
//Create a provider collection to set various processing properties
System.Collections.Generic.Dictionary<string, object> providers = new System.Collections.Generic.Dictionary<string, object>();
//Set the image base. This will be prepended to the SRC so watch your forward slashes
providers.Add(HTMLWorker.IMG_BASEURL, "http://YOUR_DOMAIN");
//Bind the providers to the worker
worker.SetProviders(providers);
worker.Parse(reader);
Below is a full working C# 2010 WinForms app targeting iTextSharp 5.1.2.0 that shows how to use a relative image and set its base using the global provider. Everything is pretty much the same as your code, although I through in a bunch of using statements to ensure proper cleanup. Make sure to watch the leading and trailing forward slashes on everything, the base URL gets prepended directly only the SRC attribute and you might end up with double-slashes if its not done correctly. I'm hard-balling a domain in here but you should be able to easily use the System.Web.HttpContext.Current.Request object.
using System;
using System.IO;
using System.Windows.Forms;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string html = #"<img src=""/images/home_mississippi.jpg"" />";
string outputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "HtmlTest.pdf");
using (FileStream fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
using (Document doc = new Document(PageSize.TABLOID)) {
using (PdfWriter writer = PdfWriter.GetInstance(doc, fs)) {
doc.Open();
using (StringReader reader = new StringReader(html)) {
using (HTMLWorker worker = new HTMLWorker(doc)) {
//Create a provider collection to set various processing properties
System.Collections.Generic.Dictionary<string, object> providers = new System.Collections.Generic.Dictionary<string, object>();
//Set the image base. This will be prepended to the SRC so watch your forward slashes
providers.Add(HTMLWorker.IMG_BASEURL, "http://www.vendiadvertising.com");
//Bind the providers to the worker
worker.SetProviders(providers);
worker.Parse(reader);
}
}
doc.Close();
}
}
}
this.Close();
}
}
}
I want to display a PDF file onto my JSF page, I have check this how to display a pdf document in jsf page in iFrame, but I dont want to display it on an iframe(since it will generate scroll bar). I just want to display the pdf onto a page like an image and able to give a width and height for it.
EDIT Hi BalusC. I still cant be able to display the pdf inline. Here is my code.
#WebServlet(name = "pdfHandler", urlPatterns = {"/pdfHandler/*"})
public class pdfHandler extends HttpServlet {
private static final int DEFAULT_BUFFER_SIZE = 10240;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String requestedFile = request.getPathInfo();
File file = new File("/Users/KingdomHeart/Downloads/Test/pdf/" + requestedFile);
response.reset();
response.setContentType("application/pdf");
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
BufferedInputStream input = null;
BufferedOutputStream output = null;
try{
input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while((length = input.read(buffer)) > 0){
output.write(buffer, 0, length);
}
}finally{
output.close();
input.close();
}
}
...
}
It still prompt me to download the pdf file. The pdf file that get downloaded to my computer is the correct pdf file btw. Can u spot anything wrong?
There's not really another way (expect from HTML <object> tag which would have the same "problems"), but you can just give the <iframe> a fixed size and disable the scrolling as follows:
<iframe src="foo.pdf" width="600" height="400" scrolling="no"></iframe>
If you also want to hide the (default) border, add frameBorder="0" as well.
You should take a look at ICEpdf, it creates an image on the server side, gives zooming, and other controls (demo).
Try going into Adobe Reader, and under the Options dialog there are web settings where you can indicate that you always want PDF type documents to open within the browser.
This is unfortunately a client side fix and doesn't take into account other PDF readers.
What you want is impossible. Browsers are not magic, they just display different kinds of documents, some of which (HTML) can embed objects provided by plugins (flash, java) and other documents inside iframes (pdf, flash, html). If you want to show pdf miniatures, you will have to generate images on the server.