The image I add to a header doesn't appear - html

I'm trying to create a header with an image; the header is added, but the image is missing in header. My application is deployed on an Oracle Weblogic server (using Java EE and Hibernate).
I'm trying to create the image like this. getImage(seasonalFilter.getPictureFileId()).getAbsolutePath(). The image path is something like this: /tmp/6461346546165461313_65464.jpg.
Note that I want to add text under the image in the header (for every page).
public File convertHtmlToPdf(String JSONString, ExportQueryTypeDTO queryType, String htmlText, ExportTypeDTO type) throws VedStatException {
try {
File retFile = null;
FilterDTO filter = null;
HashMap<Object, Object> properties = new HashMap<Object, Object>(queryType.getHashMap());
filter = JSONCoder.decodeSeasonalFilterDTO(JSONString);
DateFormat formatter = new SimpleDateFormat("yyyy_MM_dd__HH_mm");
//logger.debug("<<<<<< HTML TEXT: " + htmlText + " >>>>>>>>>>>>>>>>");
StringBuilder tmpFileName = new StringBuilder();
tmpFileName.append(formatter.format(new Date()));
retFile = File.createTempFile(tmpFileName.toString(), type.getSuffix());
OutputStream out = new FileOutputStream(retFile);
com.lowagie.text.Document document = new com.lowagie.text.Document(com.lowagie.text.PageSize.LETTER);
com.lowagie.text.pdf.PdfWriter pdfWriter = com.lowagie.text.pdf.PdfWriter.getInstance(document, out);
document.open();
com.lowagie.text.html.simpleparser.HTMLWorker htmlWorker = new com.lowagie.text.html.simpleparser.HTMLWorker(document);
String str = htmlText.replaceAll("ű", "û").replaceAll("ő", "õ").replaceAll("Ő", "Õ").replaceAll("Ű", "Û");
htmlWorker.parse(new StringReader(str));
if (filter instanceof SeasonalFilterDTO) {
SeasonalFilterDTO seasonalFilter = (SeasonalFilterDTO) filter;
if (seasonalFilter.getPictureFileId() != null) {
logger.debug("Image absolutePath: " + getImage(seasonalFilter.getPictureFileId()).getAbsolutePath());
Image logo = Image.getInstance(getImage(seasonalFilter.getPictureFileId()).getAbsolutePath());
logo.setAlignment(Image.MIDDLE);
logo.setAbsolutePosition(0, 0);
logo.scalePercent(100);
Chunk chunk = new Chunk(logo, 0, 0);
HeaderFooter header = new HeaderFooter(new Phrase(chunk), true);
header.setBorder(Rectangle.NO_BORDER);
document.setHeader(header);
}
}
document.close();
return retFile;
} catch (Exception e) {
throw new VedStatException(e);
}
}

I really dislike your false allegation that "Every tutorial is based on C:\imagelocation\dsadsa.jpg"
I'm the author of two books and many tutorials about iText and I know for a fact that what you say doesn't make any sense. Take a look at my name: "Bruno Lowagie." You are using my name in your code, so please believe me when I say you're doing it completely wrong.
Instead of HTMLWorker, you should use XML Worker. HTMLWorker is no longer supported and will probably be removed from iText in the near future.
I see that you're also using the HeaderFooter class. This class has been removed several years ago. Please take a look at the newer examples: http://www.itextpdf.com/themes/keyword.php?id=221
These examples are written in Java; if you need the C# version, please look for the corresponding C# examples in the SVN repository.
Regarding images, you may want to read chapter 10 of my book.
Finally: please read http://lowagie.com/itext2

Related

Use JSP & HTML to read file and change display options?

I want to import a text file (not user import), for example:
Coding
There are several languages...
When the file is read, the first line should be in larger font and bolded, and the other lines can be kept in the text file format. Not sure how I can use JSP and link it to HTML
You've left out a lot of important details (Q: How is the JSP getting invoked? Q: Are you passing a filename in the URL? Etc. etc.)
But here's a simple example that might get you started in the right direction:
<%
BufferedReader reader = new BufferedReader(new FileReader("myile.txt"));
boolean firstLine = true;
String line;
while((line = reader.readLine())!= null){
if (firstLine) {
line = "<b>" + line + "</b>";
firstLine = false;
}
out.println(line);
}
reader.close();
%>

convert html to word not working as example

I am trying to convert html to word. I have found so many codes over the net but none of them works. They are worked with string builder or some with others. I have given a code. In debugger it goes through all the codes without error but no file is getting downloaded.
public void converToWord(string htmlContent,string name)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentType = "application/msword";
string strFileName = name + ".doc";
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline;filename=" + strFileName);
StringBuilder strHTMLContent = new StringBuilder();
strHTMLContent.Append("<html xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:word\" xmlns=\"http://www.w3.org/TR/REC-html40\"><head></head><body>");
strHTMLContent.Append(htmlContent);
strHTMLContent.Append("</body></html>");
HttpContext.Current.Response.Write(strHTMLContent);
HttpContext.Current.Response.End();
HttpContext.Current.Response.Flush();
}
i got an error it says {Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.}
while the button is in update panel and it does not work properly.everything seems fine but it does not get downloaded.it is a very common problem that happens.just put o a trigger to the button that is firing the event and it will start to work just very much fine.

Getting date in CSS and HTML to PDF's footer

Im using ITextRenderer to generate a pdf file from html and css, I have a footer with the current page on the right.
But now i would like to have the current date on the left.
I found this:
<div data-line="1"></div>
div[data-line]:after {
content: "[line " attr(data-line) "]";
}
But I dont know how to combine it with :
#bottom-left {
content: "Date: ";
}
Is this possible or is there any other way?
I would like the footer to look something like this:
Date: 2015-03-17 12:04
UPDATE 1:
I have a method createPDF(string html, String resourceUrl), that looks like this:
ByteArrayOutputStream out = new ByteArrayOutputStream();
HtmlCleaner cleaner = new HtmlCleaner();
TagNode node = cleaner.clean(html);
CleanerProperties props = cleaner.getProperties();
new SimpleXmlSerializer(props).writeToStream(node, out, "ISO-8859-1");
ITextRenderer renderer = new ITextRenderer();
renderer.setPDFVersion(PdfWriter.VERSION_1_7);
renderer.setDocumentFromString(new String(out.toByteArray(), "ISO-8859-1"));
renderer.getSharedContext().setBaseURL(resourceUrl);
renderer.layout();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
renderer.createPDF(outputStream);
renderer.finishPDF();
outputStream.flush();
outputStream.close();
return outputStream.toByteArray();
The example that you cite of using data-line in the CSS is an interesting way to dynamically generate CSS based on data-* HTML attributes. These in turn might be dynamically generated in a web page by a server-side or client-side script. But it seems like this might not be the appropriate method for your case.
If you are already using a Java class like ITextRenderer to generate this PDF, then the best method for you is probably just to use Java itself to generate the current date in the format that you want, then print that directly into the CSS as a string.
If you are loading the CSS from a manually created file, one way to do this would be to write your CSS with some text you intend to replace, for example INSERTDATE. Then in Java, load your document the way you normally do, then use some Java code like String.replace() to replace INSERTDATE with today's date.
Update 1:
Based on your sample code above, you could write INSERTDATE where you want the date to appear in your HTML/CSS, then call:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); # your desired format
String strDate = sdf.format(new Date()); # get the current date
html = html.replace("INSERTDATE", strDate);
at the top of your method.
You can use css string-set with content() and string() css functions , see https://www.w3.org/TR/css-gcpm-3/ like :
<div class="where-content-comes-from">1</div>
<div class="where-content-is-injected"></div>
.where-content-comes-from{
display:none;
string-set: am-just-a-var content();
}
.where-content-is-injected:after {
content: string(am-just-a-var);
}
bonus : you can also use css env() function to display date value see https://developer.mozilla.org/en-US/docs/Web/CSS/env

Parsing html page content without using selector

I am going to parse some web pages using Java program. For this purpose I wrote a small code for parsing page content by using xpath as selector. For parsing different sites you need to find the appropriate xpath per each site. The problem is for doing that you need an operator to find the write xpath for you. (for example using firepath firefox addon) Suppose you dont know what page you should parse or the number of sites get really big for operator to find right xpath. In this case you need a way for parsing pages without using any selector. (same scenario exist for CSS selector) Or there should be a way to find xpath automatically! I was wondering what is the method of parsing web pages in this way?
Here is the small code which I wrote for this purpose, please feel free to extend that in presenting your solutions.
public downloadHTML(String url) throws IOException{
CleanerProperties props = new CleanerProperties();
// set some properties to non-default values
props.setTranslateSpecialEntities(true);
props.setTransResCharsToNCR(true);
props.setOmitComments(true);
// do parsing
TagNode tagNode = new HtmlCleaner(props).clean(
new URL(url)
);
// serialize to xml file
new PrettyXmlSerializer(props).writeToFile(
tagNode, "c:\\TEMP\\clean.xml", "utf-8"
);
}
public static void testJavaxXpath(String pattern)
throws ParserConfigurationException, SAXException, IOException,
FileNotFoundException, XPathExpressionException {
DocumentBuilder b = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
org.w3c.dom.Document doc = b.parse(new FileInputStream(
"c:\\TEMP\\clean.xml"));
// Evaluate XPath against Document itself
javax.xml.xpath.XPath xPath = XPathFactory.newInstance().newXPath();
NodeList nodes = (NodeList) xPath.evaluate(pattern,
doc.getDocumentElement(), XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); ++i) {
Element e = (Element) nodes.item(i);
System.out.println(e.getFirstChild().getTextContent());
}
}

Add title to pdf using itext

{
Document document = new Document(PageSize.A3, 32, 32, 32, 32);
PdfWriter.getInstance(document, response.getOutputStream());
document.open();
HTMLWorker htmlWorker = new HTMLWorker(document);
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db", "", "");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("Select * from test3");
List arrlist = new ArrayList();
while(rs.next()){
String xa =rs.getString("display");
if(xa.equals("1")){
arrlist.add(rs.getString("question_text"));
}
}
Collections.shuffle(arrlist);
for(int i=0;i<5;i++){
String str = (String) arrlist.get(i);
htmlWorker.parse(new StringReader(str));
htmlWorker.parse(new StringReader("<br>"));
}
document.close();
}
Above is a code snippet which gets data from the database and displays on pdf.How do I add a title, logo,date and page no.to this?Please if anyone could help.I am using itext.
Please check out some of the page event examples. Currently, you're creating an unnamed PdfWriter instance. Change this into a named writer instance and declare a page event before opening the document instance:
PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
writer.setPageEvent(new MyPageEvents());
The MyPageEvents class is to be written by you. It needs to implement the PdfPageEvent interface, or, better yet, extend the PdfPageEventHelper class.
Adding a title, logo, date,... in the header is done by implementing the onEndPage() method. Do NOT use the onStartPage() method without reading the documentation!!!
Use these onEndPage() examples for inspiration.
To add an Image, add a member variable img to your page event, and add this to your constructor:
Image img = Image.getInstance(pathToImage);
img.setAbsolutePosition(36, 806);
Then in the onEndPage() method, do this:
writer.getDirectContent().addImage(img);
This will add the image at position x = 36, y = 806 (near the left top of the page). Note that it's important that you don't create a new Image instance for every new page, because that would result in a bloated PDF file. By creating the Image in the constructor of your page event and reusing the object, the image bytes will be present only once in the PDF file.