I try convert docx to pdf.
Docx file has korean
maybe you think BTS song's lyrics
Eg.
Friends
BTS
유난히도 반짝였던 서울!
처음 보는 또 다른 세상
땀에 잔뜩 밴 채 만난 넌
뭔가 이상했었던 아이
난 달에서, 넌 별에서
우리 대화는 숙제 같았지
하루는 베프, 하루는 웬수
I just wanna understand
Hello my alien
우린 서로의 mystery
그래서 더 특별한 걸까
언젠가 이 함성 멎을 때 stay, hey
내 옆에 함께 있어줘
영원히 계속 이곳에 stay, hey
네 작은 새끼손가락처럼
일곱 번의 여름과 추운 겨울보다
오래
수많은 약속과 추억들보다
this is my convering code.
String k=null;
OutputStream fileForPdf =null;
try {
String fileName=w;
//Below Code is for .doc file
if(fileName.endsWith(".doc"))
{
HWPFDocument doc = new HWPFDocument(new FileInputStream(
fileName));
WordExtractor we=new WordExtractor(doc);
k = we.getText();
fileForPdf = new FileOutputStream(new File(
p));
we.close();
}
//Below Code for
else if(fileName.endsWith(".docx"))
{
XWPFDocument docx = new XWPFDocument(new FileInputStream(
fileName));
// using XWPFWordExtractor Class
XWPFWordExtractor we = new XWPFWordExtractor(docx);
k = we.getText();
fileForPdf = new FileOutputStream(new File(p));
we.close();
}
Document document = new Document();
PdfWriter.getInstance(document, fileForPdf);
document.open();
document.add(new Paragraph(k));
document.close();
fileForPdf.close();
this code make pdf file But this file didn't have korea lyrics
You can try the following approach to convert a .docx file to .pdf file.
https://simplesolution.dev/java-convert-docx-file-to-pdf-file-using-xdocreport/
import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
public class FileConverter {
public void convertWordToPdf(String docxFileName, String pdfFileName) {
try(InputStream inputStream = new FileInputStream(docxFileName);
OutputStream outputStream = new FileOutputStream(pdfFileName)) {
XWPFDocument document = new XWPFDocument(inputStream);
PdfOptions options = PdfOptions.create();
// Convert .docx file to .pdf file
PdfConverter.getInstance().convert(document, outputStream, options);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
String docxFileName = "D:\\SimpleSolution\\Data\\Document.docx";
String pdfFileName = "D:\\SimpleSolution\\Data\\Document.pdf";
FileConverter fileConverter = new FileConverter();
fileConverter.convertWordToPdf(docxFileName, pdfFileName);
Related
i want to convert docx to pdf using apache-poi and itext 7(pdf calligraph on)
i have tried using other version of itext but they are showing problem of ligature in indic languages
import org.apache.poi.xwpf.converter.pdf.PdfConverter;
import org.apache.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.util.FileCopyUtils;
import java.io.*;
public class Docx2PdfConverterUsingPOI implements Docx2PdfConverter{
public byte[] convert(byte[] docxData) {
byte[] output = null;
try {
InputStream isFromFirstData = new ByteArrayInputStream(docxData);
XWPFDocument document = new XWPFDocument(isFromFirstData);
PdfOptions pdfOptions = PdfOptions.create();
// pdfOptions.fontEncoding(BaseFont.IDENTITY_H);
//make new file in c:\temp\
ByteArrayOutputStream out = new ByteArrayOutputStream();
//Options options =
Options.getTo(ConverterTypeTo.PDF).via(ConverterTypeVia.XWPF).
subOptions(pdfOptions);
PdfConverter.getInstance().convert(document, out, pdfOptions);
document.close();
return out.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return output;
}
public static void main(String args[]){
Docx2PdfConverterUsingPOI docx2PdfConverterUsingPOI =new
Docx2PdfConverterUsingPOI();
String inputFile = "D:\\WORKSPACE\\yogesh\\letters\\out.docx";
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(new File(inputFile));
byte[]output =
docx2PdfConverterUsingPOI.convert(FileCopyUtils.
copyToByteArray(inputStream));
FileCopyUtils.copy(output,new
File("D:\\WORKSPACE\\yogesh\\letters\\out1.pdf"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
can anyone help me in how to use itext7 with apache poi for my docx to pdf conversion.
Also,can anyone explain how apache uses itext to get proper result of conversion(so that i can change the itext maven dependency accordingly)
Details : When i hit a URL it gives me a jsp page which needs to be converted in to a PDF. for now am using ITextPDF in java component for reading the jsp and writing it as PDF. Is there any alternative process within mule without using ITextPDF.
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.mule.api.MuleEventContext;
import org.mule.api.lifecycle.Callable;
import org.mule.api.transport.PropertyScope;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
public class PDFConversion implements Callable {
private final String USER_AGENT = "Mozilla/5.0";
StringBuffer response = new StringBuffer();
ByteArrayOutputStream bos;
byte[] result;
#Override
public Object onCall(MuleEventContext eventContext) throws Exception {
try {
String productid="";
String vertical="";
String postcode="";
String metertype="";
String includeSolar="";
productid=eventContext.getMessage().getInvocationProperty("productId");
vertical=eventContext.getMessage().getInvocationProperty("vertical");
postcode=eventContext.getMessage().getInvocationProperty("postcode");
metertype=eventContext.getMessage().getInvocationProperty("metertype");
includeSolar=eventContext.getMessage().getInvocationProperty("includeSolar");
String url = "http://191.111.0.111:****/PDFService/electricitypdf?productid="+productid+"&vertical="+vertical+"&postcode="+postcode+"&metertype="+"&includeSolar="+includeSolar;
System.out.println(" URL -Request-----"+url);
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
// add request header
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
bos = new ByteArrayOutputStream();
int next = in.read();
while (next > -1) {
bos.write(next);
next = in.read();
}
bos.flush();
/ ByteArrayOutputStream buffer = new ByteArrayOutputStream(); byte[] bytes = IOUtils.toByteArray(in); while ((inputLine = in.readLine()) != null) { response.append(inputLine); }/ in.close();
} catch (Exception e) {
e.printStackTrace();
}
Document document = new Document(PageSize.LETTER, 0.75F, 0.75F, 0.75F, 0.75F);
document.setPageSize(PageSize.LETTER.rotate());
// PdfWriter.setPageEvent(new HeaderFooter(mmPDFDocument.right() -
// mmPDFDocument.left(), footer, path, headerType, unicodeFont));
PdfWriter.getInstance(document, bos);
document.open();
int numberpages=10;
for (int i = 1; i <= numberpages; i++)
{
document.add(new Chunk("Hello PDF Service - Page "+i));
document.newPage();
}
FileOutputStream fos= new FileOutputStream("energy.pdf");
fos.write(bos.toByteArray());
fos.close();
document.close();
return bos;
}
}
Despite writing this the browser is unable to display the content as PDF i could see that the PDF file is being written and when the URL is hit it generates a file of no type(not a pdf). any help appreciated !!
Your solution is basically a standard Java Application running on Mule ESB. Mule is for message based communication and transformations. If you wanted to turn your solution into a full "Mule Solution" I would recommend....
Use an http:request directive to call the jsp page to return back html.
Example here: Mule ESB : Read HTML
Write a transformer to transform the text/html message to a byte array (or some other type) this will have to be done using ITextPDF.
Output the byte array to a file.
You basically are doing the correct steps but not using any advantages of the Mule platform. When you separate the solution out this way you will be able to write the pdf file easily and not get any strange results.
I am dynamically creating a PDF document, add a signature field and afterwards trying to sign it. The signing works properly, but i am getting an exception:
"certfied by %, invalid signature and signature contains invalid data"
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.Security;
import java.security.cert.Certificate;
import java.util.Calendar;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfSignatureAppearance;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.security.BouncyCastleDigest;
import com.itextpdf.text.pdf.security.ExternalDigest;
import com.itextpdf.text.pdf.security.ExternalSignature;
import com.itextpdf.text.pdf.security.MakeSignature;
import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard;
import com.itextpdf.text.pdf.security.PrivateKeySignature;
//Actual class
public class SignPdf {
// Signs the pdf
public void signPdf(String src, String dest, boolean certified, boolean graphic) throws GeneralSecurityException, IOException, DocumentException{
String path = "src/certs.pfx";
String keystore_password = "pwd";
String key_password = "pwd";
KeyStore ks = KeyStore.getInstance("PKCS12", new org.bouncycastle.jce.provider.BouncyCastleProvider());
InputStream is = this.getClass().getResourceAsStream("/certs.pfx");
ks.load(is, keystore_password.toCharArray());
String alias = ks.aliases().nextElement();
PrivateKey pk = (PrivateKey) ks.getKey(alias, key_password.toCharArray());
Certificate[] chain = ks.getCertificateChain(alias);
byte[] pdfByteArray = null;
// creating dynamic document using itext.
Document document = new Document();
OutputStream baosPDF = new ByteArrayOutputStream();
PdfWriter.getInstance(document, baosPDF);
document.open();
document.add(new Paragraph("Hello World!"));
document.close();
byte[] bytearrayb = ((ByteArrayOutputStream) baosPDF).toByteArray();
PdfReader reader = new PdfReader(bytearrayb);
PdfStamper stamper = PdfStamper.createSignature(reader, baosPDF, '\0', null, true);
PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
appearance.setReason("Security");
appearance.setLocation("Footer");
appearance.setVisibleSignature(new Rectangle(100, 100, 200, 200), 1, "DVA");
if (certified) appearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);
if (graphic) {
appearance.setSignatureGraphic(Image.getInstance(RESOURCE));
appearance.setRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC);
}
appearance.setSignDate(Calendar.getInstance());
appearance.setSignatureCreator("test");
ExternalSignature es = new PrivateKeySignature(pk, "SHA-256", "BC");
ExternalDigest digest = new BouncyCastleDigest();
MakeSignature.signDetached(appearance, digest, es, chain, null, null, null, 0, CryptoStandard.CMS);
baosPDF.flush();
baosPDF.close();
BufferedOutputStream fs = new BufferedOutputStream(new FileOutputStream(new File("myFile121.pdf")));
fs.write(((ByteArrayOutputStream) baosPDF).toByteArray());
fs.flush();
fs.close();
}
public static void main(String[] args) throws Exception {
Security.addProvider(new BouncyCastleProvider());
SignPdf signatures = new SignPdf();
try {
signatures.signPdf(ORIGINAL, "", true, false);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
You re-use the ByteArrayOutputStream without clearing it:
OutputStream baosPDF = new ByteArrayOutputStream();
PdfWriter.getInstance(document, baosPDF);
document.open();
document.add(new Paragraph("Hello World!"));
document.close();
byte[] bytearrayb = ((ByteArrayOutputStream) baosPDF).toByteArray();
PdfReader reader = new PdfReader(bytearrayb);
PdfStamper stamper = PdfStamper.createSignature(reader, baosPDF, '\0', null, true);
According to the ByteArrayOutputStream source:
/**
* Resets the <code>count</code> field of this byte array output
* stream to zero, so that all currently accumulated output in the
* output stream is discarded. The output stream can be used again,
* reusing the already allocated buffer space.
*
* #see java.io.ByteArrayInputStream#count
*/
public synchronized void reset()
Thus, reset before re-use:
byte[] bytearrayb = ((ByteArrayOutputStream) baosPDF).toByteArray();
baosPDF.reset();
PdfReader reader = new PdfReader(bytearrayb);
PdfStamper stamper = PdfStamper.createSignature(reader, baosPDF, '\0', null, true);
I am trying to read Greek from a pdf file using PDFbox 1.8.7. The issue is that whatever encoding I use (Windows-1253, ISO-8859-7,UTF-8) I cannot read the greek characters. Could you provide me with an insight on what I need to set differently in the options of PDFbox in order to read the greek characters. (sample pdf file here https://www.wetransfer.com/downloads/861b3c85bb2b1eca9f10af210a8eff4820141111223938/83ff55)
My source code is the following:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDTrueTypeFont;
import org.apache.pdfbox.util.PDFText2HTML;
import org.apache.pdfbox.util.PDFTextStripper;
/**
*
* #author Administrator
*/
public class Pdf {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
try {
PDFTextStripper pdfStripper = null;
PDDocument pdDoc = null;
COSDocument cosDoc = null;
File file = new File("C:\\themis\\Pdfs\\first.pdf");
PDFParser parser = new PDFParser(new FileInputStream(file));
parser.parse();
cosDoc = parser.getDocument();
pdDoc = new PDDocument(cosDoc);
String encoding="ISO-8859-7";
pdfStripper = new PDFTextStripper(encoding);
pdfStripper.setStartPage(1);
pdfStripper.setEndPage(2);
String parsedText = pdfStripper.getText(pdDoc);
System.out.println(parsedText);
} catch (FileNotFoundException ex) {
Logger.getLogger(PdfBMW.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(PdfBMW.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
I'm currently developing a method that will accept HTML input and convert it into a valid PDF/A file. I know how to programmatically construct a valid PDF/A file using iText (reference: http://itextsupport.com/download/pdfa3.html) but I'm unable to generate a valid PDF/A file using HTML as input and using XMLWorker to transform this input into a PDF file. The problem that I have right now is due to the embedded fonts requirement of the PDF/A format. I always get this exception:
Exception in thread "main" com.itextpdf.text.pdf.PdfAConformanceException: All the fonts must be embedded. This one isn't: Helvetica
I try to force which fonts will the HTML input use via a CSS file and I register the fonts I want to use in the output PDF file via the XMLWorkerFontProvider class, but it seems I'm doing something wrong because the exception commented above is always thrown.
What else do I need in order to XMLWorker uses the fonts registered via XMLWorkerFontProvider class? I want to avoid the use of the default font Helvetica in every HTML element present in the input.
Below is the code I'm using for testing:
style.css (just 1 line):
* { font: normal 100% Arial, sans-serif !important; }
Main.java:
package com.itextpdf;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringReader;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.ICC_Profile;
import com.itextpdf.text.pdf.PdfAConformanceLevel;
import com.itextpdf.text.pdf.PdfAWriter;
import com.itextpdf.tool.xml.XMLWorker;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.itextpdf.tool.xml.css.CssFile;
import com.itextpdf.tool.xml.css.StyleAttrCSSResolver;
import com.itextpdf.tool.xml.html.CssAppliers;
import com.itextpdf.tool.xml.html.CssAppliersImpl;
import com.itextpdf.tool.xml.html.Tags;
import com.itextpdf.tool.xml.parser.XMLParser;
import com.itextpdf.tool.xml.pipeline.css.CSSResolver;
import com.itextpdf.tool.xml.pipeline.css.CssResolverPipeline;
import com.itextpdf.tool.xml.pipeline.end.PdfWriterPipeline;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipeline;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipelineContext;
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
StringBuffer buf = new StringBuffer();
buf.append("<!DOCTYPE html>");
buf.append("<html>");
buf.append("<head>");
buf.append("<title>Test</title>");
buf.append("</head>");
buf.append("<body>");
buf.append("<p>This is a test</p>");
buf.append("</body>");
buf.append("</html>");
OutputStream file = null;
Document document = null;
PdfAWriter writer = null;
try {
file = new FileOutputStream(new File("C:\\Users\\amartin\\Desktop\\Test.pdf"));
document = new Document();
writer = PdfAWriter.getInstance(document, file, PdfAConformanceLevel.PDF_A_1B);
// Create XMP metadata. It's a PDF/A requirement.
writer.createXmpMetadata();
document.open();
// Set output intent. PDF/A requirement.
ICC_Profile icc = ICC_Profile.getInstance(new FileInputStream("./src/main/resources/com/itextpdf/sRGB Color Space Profile.icm"));
writer.setOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);
// CSS
CSSResolver cssResolver = new StyleAttrCSSResolver();
CssFile cssFile = XMLWorkerHelper.getCSS(new FileInputStream("./css/style.css"));
cssResolver.addCss(cssFile);
XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider();
fontProvider.register("./fonts/arial.ttf");
fontProvider.register("./fonts/sans-serif.ttf");
fontProvider.addFontSubstitute("lowagie", "garamond");
CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);
HtmlPipelineContext htmlContext = new HtmlPipelineContext(cssAppliers);
htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
// Pipelines
PdfWriterPipeline pdf = new PdfWriterPipeline(document, writer);
HtmlPipeline html = new HtmlPipeline(htmlContext, pdf);
CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);
XMLWorker worker = new XMLWorker(css, true);
XMLParser p = new XMLParser(worker);
Reader reader = new StringReader(buf.toString());
p.parse(reader);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (document != null && document.isOpen())
document.close();
try {
if (file != null)
file.close();
} catch (IOException e) {}
if (writer != null && !writer.isCloseStream())
writer.close();
}
}
}
edit:
Answering to Bruno, I have extended the FontFactoryImp class overriding the getFont() method (the one that has all the arguments). It calls the the System.out.println function like this:
System.out.println("=fontname: " + fontname + " =encoding: " + encoding + " =embedded : " + embedded + " =size: " + size + " =style: " + style + " =BaseColor: " + color)
and then calls parent.getFont() method with the same arguments. The only output I see is this:
=fontname: null =encoding: Cp1252 =embedded : true =size: -1.0 =style: -1 =BaseColor: null
=fontname: null =encoding: Cp1252 =embedded : true =size: -1.0 =style: -1 =BaseColor: null
and the exception thrown, pasted before this code.
Based on the feedback you're sending to the System.out, it seems that XML Worker doesn't pick up the font family you want to use.
Please specify the font family like this:
font-family: "Arial"
Using 'font' in CSS may work, but it's tricky. I think iText sees normal and interprets it as Use the default font.
The complete code that makes this example work is the following:
style.css:
* {
font-family: "Arial";
font-style: normal;
}
Main.java:
package com.itextpdf;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringReader;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.ICC_Profile;
import com.itextpdf.text.pdf.PdfAConformanceLevel;
import com.itextpdf.text.pdf.PdfAWriter;
import com.itextpdf.tool.xml.XMLWorker;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.itextpdf.tool.xml.css.CssFile;
import com.itextpdf.tool.xml.css.StyleAttrCSSResolver;
import com.itextpdf.tool.xml.html.CssAppliers;
import com.itextpdf.tool.xml.html.CssAppliersImpl;
import com.itextpdf.tool.xml.html.Tags;
import com.itextpdf.tool.xml.parser.XMLParser;
import com.itextpdf.tool.xml.pipeline.css.CSSResolver;
import com.itextpdf.tool.xml.pipeline.css.CssResolverPipeline;
import com.itextpdf.tool.xml.pipeline.end.PdfWriterPipeline;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipeline;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipelineContext;
public class Main {
public static void main(String[] args) {
StringBuffer buf = new StringBuffer();
String title = "Test";
// Sample HTML content.
buf.append("<!DOCTYPE html>");
buf.append("<html>");
buf.append("<head>");
buf.append("<title>" + title + "</title>");
buf.append("</head>");
buf.append("<body>");
buf.append("<p>This is a test</p>");
buf.append("</body>");
buf.append("</html>");
OutputStream file = null;
Document document = null;
PdfAWriter writer = null;
try {
file = new FileOutputStream(new File("C:\\Users\\amartin\\Desktop\\Test.pdf"));
document = new Document();
writer = PdfAWriter.getInstance(document, file, PdfAConformanceLevel.PDF_A_1B);
// Avoid discrepances between document title and XMP metadata information.
document.addTitle(title);
// Create XMP metadata. It's a PDF/A requirement.
writer.createXmpMetadata();
document.open();
// Set output intent. PDF/A requirement.
ICC_Profile icc = ICC_Profile.getInstance(new FileInputStream("./src/main/resources/com/itextpdf/sRGB Color Space Profile.icm"));
writer.setOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);
// CSS stylesheet.
CSSResolver cssResolver = new StyleAttrCSSResolver();
CssFile cssFile = XMLWorkerHelper.getCSS(new FileInputStream("./css/style.css"));
cssResolver.addCss(cssFile);
MyFontProvider fontProvider = new MyFontProvider();
fontProvider.register("./fonts/arial.ttf");
/* DEBUG
System.out.println("Fonts present in " + fontProvider.getClass().getName());
Set<String> registeredFonts = fontProvider.getRegisteredFonts();
for (String font : registeredFonts)
System.out.println(font);
*/
CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);
HtmlPipelineContext htmlContext = new HtmlPipelineContext(cssAppliers);
htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
// Pipelines.
PdfWriterPipeline pdf = new PdfWriterPipeline(document, writer);
HtmlPipeline html = new HtmlPipeline(htmlContext, pdf);
CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);
XMLWorker worker = new XMLWorker(css, true);
XMLParser p = new XMLParser(worker);
Reader reader = new StringReader(buf.toString());
p.parse(reader);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (document != null && document.isOpen())
document.close();
try {
if (file != null)
file.close();
} catch (IOException e) {}
if (writer != null && !writer.isCloseStream())
writer.close();
}
}
}
MyFontProvider.java:
package com.itextpdf;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactoryImp;
public class MyFontProvider extends FontFactoryImp {
#Override
public Font getFont(String fontname, String encoding, boolean embedded,
float size, int style, BaseColor color) {
System.out.println("=fontname: " + fontname + " =encoding: " + encoding + " =embedded : " + embedded + " =size: " + size + " =style: " + style + " =BaseColor: " + color);
return super.getFont(fontname, encoding, embedded, size, style, color);
}
}
Again, thank you, Bruno. I'm really glad to get your help here :)