I am using Docx4j in an internship project and when I try to generate a ToC with page numbers it does not work.
Executing the code with
if (template.isGenerateToc()) {
Toc.setTocHeadingText("Inhaltsverzeichnis");
TocGenerator tocGenerator = new TocGenerator(wordPackage);
tocGenerator.generateToc(2, " TOC \\o \"1-3\" \\h \\z \\u ", true);
}
Works perfectly fine, but results in no page numbers in the .docx (when exporting to PDF via the Gotenberg API (https://gotenberg.dev), the page numbers are existant and correct).
When I try to pass "false" for the third parameter, the application crashes with the following exception/stacktrace:
org.docx4j.toc.TocException: Exception exporting package
at org.docx4j.toc.TocGenerator.getPageNumbersMapViaFOP(TocGenerator.java:871)
at org.docx4j.toc.TocGenerator.getPageNumbersMap(TocGenerator.java:694)
at org.docx4j.toc.TocGenerator.populateToc(TocGenerator.java:441)
at org.docx4j.toc.TocGenerator.generateToc(TocGenerator.java:306)
at org.docx4j.toc.TocGenerator.generateToc(TocGenerator.java:234)
at org.docx4j.toc.TocGenerator.generateToc(TocGenerator.java:194)
If usefull: This is my TocHeading:
private static String XML_TOCHeading_BasedOn_Nothing = "<w:style w:styleId=\"TOCHeading\" w:type=\"paragraph\" xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\">"
+ "<w:name w:val=\"TOC Heading\"/>"
// + "<w:basedOn w:val=\"Heading1\"/>" // would be ok if provided already present, since
+ "<w:next w:val=\"Normal\"/>"
+ "<w:uiPriority w:val=\"39\"/>"
+ "<w:semiHidden/>"
+ "<w:unhideWhenUsed/>"
+ "<w:qFormat/>"
+ "<w:pPr>"
+ "<w:keepNext/>"
+ "<w:keepLines/>"
+ "<w:spacing w:after=\"150\" w:before=\"480\"/>"
+ "<w:outlineLvl w:val=\"9\"/>"
+ "</w:pPr>"
+ "<w:rPr>"
+ "<w:rFonts w:ascii=\"Arial\" w:hAnsi=\"Arial\" w:cs=\"Arial\"/>"
+ "<w:b/>"
+ "<w:bCs/>"
+ "<w:sz w:val=\"36\"/>"
+ "<w:szCs w:val=\"36\"/>"
+ "</w:rPr>"
+ "</w:style>";
Any ideas on how to fix this exception and generate page numbers in my toc?
EDIT:
I updated the dependencies and now I am still getting the TocException but now with another cause:
Caused by: org.docx4j.openpackaging.exceptions.Docx4JException: Exception exporting package
at org.docx4j.convert.out.common.AbstractExporter.export(AbstractExporter.java:106)
at org.docx4j.Docx4J.toFO(Docx4J.java:734)
at org.docx4j.toc.TocGenerator.getPageNumbersMapViaFOP(TocGenerator.java:843)
... 97 more
Caused by: java.lang.NullPointerException
at org.docx4j.convert.out.common.preprocess.Containerization.borderChanged(Containerization.java:390)
at org.docx4j.convert.out.common.preprocess.Containerization.bordersChanged(Containerization.java:377)
at org.docx4j.convert.out.common.preprocess.Containerization.groupBodyContent(Containerization.java:204)
at org.docx4j.convert.out.common.preprocess.Containerization.groupAdjacentBorders(Containerization.java:129)
at org.docx4j.convert.out.common.preprocess.Containerization.process(Containerization.java:120)
at org.docx4j.convert.out.common.Preprocess.process(Preprocess.java:165)
at org.docx4j.convert.out.common.AbstractWmlExporter.preprocess(AbstractWmlExporter.java:51)
at org.docx4j.convert.out.common.AbstractWmlExporter.preprocess(AbstractWmlExporter.java:32)
at org.docx4j.convert.out.common.AbstractExporter.export(AbstractExporter.java:63)
Not sure which version of docx4j you are using, but generally, to update page numbers, you need FOP on your classpath.
We broke this in 8.3.3; it is fixed at https://github.com/plutext/docx4j/commit/50cfa5cabe08ab133f28c54b59f73d082d3e80a4#diff-29cfd63b63bfe585aa3468870ca54f1afb6e2246342c396155801b0d0aa9ae43L763
So you could try 8.3.2 with FOP on your classpath.
Alternatively, you could try the approach described at https://www.docx4java.org/blog/2020/03/documents4j-for-toc-update/
See further:
documents4j-local: https://github.com/plutext/docx4j/blob/master/docx4j-samples-documents4j-local/src/main/java/org/docx4j/samples/documents4j/local/TocOperations.java
documents4j-remote: https://github.com/plutext/docx4j/tree/master/docx4j-samples-documents4j-remote
SOLVED & WHY:
Path to image contains Unicode character, I have to say it's a bug.
ORIGINAL POST:
I am new to OpenCV and just use java with OpenCV 3.2.0, 3.1.0, and 2.4.3 to read this image without any success, namely, no width or height can be read, though my aim is to find the harris corners, and use other image is without this problem.
code:
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.highgui.Highgui;
public class Test
{
public static void main (String []args)
{
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
Mat img_object = Highgui.imread("E:/ℤIMAGEℂ/ℤtestℂ.png");
System.out.println(
"img_object.width() = " + img_object.width()
+ ",\n img_object.height() = " + img_object.height()
+ ",\n img_object.depth() = " + img_object.depth()
+ ",\n img_object.channels() = " + img_object.channels()
+ ",\n img_object.total() = " + img_object.total()
+ ",\n img_object.type() = " + img_object.type()
);
}
}
Image:
error:
img_object.width() = 0,
img_object.height() = 0,
img_object.depth() = 0,
img_object.channels() = 1,
img_object.total() = 0,
img_object.type() = 0
libpng warning: Image width is zero in IHDR
libpng warning: Image height is zero in IHDR
libpng error: Invalid IHDR data
OpenCV Error: Assertion failed (code) in cv::imencode, file ..\..\..\..\opencv\modules\highgui\src\loadsave.cpp, line 430
Exception in thread "main" CvException [org.opencv.core.CvException: cv::Exception: ..\..\..\..\opencv\modules\highgui\src\loadsave.cpp:430: error: (-215) code in function cv::imencode
]
at org.opencv.highgui.Highgui.imencode_1(Native Method)
at org.opencv.highgui.Highgui.imencode(Highgui.java:243)
at Imshow.imshow(Imshow.java:29)
at test.main(Test.java:21)
SOLVED & WHY:
Path to image contains Unicode character.
As someone suggests if you solve your problem, delete it or answer it.
If you try to read image from Unicode path, errors occur, and I didn't see related solution, so you can read this.
OpenCV is bugged with Unicode file path, sadly. That's the problem of OpenCV but mine.
I've downloaded some grib data files from here: ftp://data-portal.ecmwf.int/20160721000000/ (file type is .bin) and want to extract the data from this file in my Java application (I want to load the extracted data into a database later). I'm just trying with the file ftp://wmo:essential#data-portal.ecmwf.int/20160721000000/A_HWXE85ECEM210000_C_ECMF_20160721000000_24h_em_ws_850hPa_global_0p5deg_grib2.bin.
Therefore I've created a new Java project and added the two libraries grib-8.0.29.jar and netcdfAll-4.6.6.jar. Documentation for the grib API can be found here: http://www.unidata.ucar.edu/software/decoders/grib/javadoc/. I need to open the downloaded files to get the data. Retrieving some metadata via Grib2Dump seems to work (see below). Also the Grib2Input instance sais, that I have a valid GRIB file of version 2.
Here my working code for retrieving some metadata:
public static void main(String[] args) throws IOException, InterruptedException {
File srcDir = new File("C://test//");
File[] localFiles = srcDir.listFiles();
for (File tempFile : localFiles) {
RandomAccessFile raf = new RandomAccessFile(tempFile.getAbsolutePath(), "r");
System.out.println("======= Grib2GDSVariables ==========");
Grib2GDSVariables gdsVariables = new Grib2GDSVariables(raf.readBytes(raf.read()));
System.out.println("Gds key : " + gdsVariables.getGdsKey());
System.out.println("======= Grib2Input ==========");
Grib2Input input = new Grib2Input(raf);
System.out.println(Grib2Input.isValidFile(raf));
System.out.println("scan : " + input.scan(true, true));
System.out.println("getGDSs.size: " + input.getGDSs().size());
System.out.println("getProducts.size: " + input.getProducts().size());
System.out.println("getRecords.size: " + input.getRecords().size());
System.out.println("edition: " + input.getEdition());
System.out.println("======= Grib2Dump ==========");
Grib2Dump dump = new Grib2Dump();
dump.gribDump(new String[] {tempFile.getAbsolutePath()});
System.out.println("======= Grib2ExtractRawData ==========");
Grib2ExtractRawData extractRawData = new
Grib2ExtractRawData(raf); extractRawData.main(new String[] {tempFile.getAbsolutePath()});
}
System.out.println("finished");
}
This produces the following output:
======= Grib2GDSVariables ==========
Gds key : -1732955898
======= Grib2Input ==========
true
scan : true
getGDSs.size: 0
getProducts.size: 0
getRecords.size: 0
edition: 2
======= Grib2Dump ==========
--------------------------------------------------------------------
Header : GRIB2
Discipline : 0 Meteorological products
GRIB Edition : 2
GRIB length : 113296
Originating Center : 98 European Center for Medium-Range Weather Forecasts (RSMC)
Originating Sub-Center : 0
Significance of Reference Time : 1 Start of forecast
Reference Time : 2016-07-21T00:00:00Z
Product Status : 0 Operational products
Product Type : 1 Forecast products
Number of data points : 259920
Grid Name : 0 Latitude_Longitude
Grid Shape: 6 Earth spherical with radius of 6,371,229.0 m
Number of points along parallel: 720
Number of points along meridian: 361
Basic angle : 0
Subdivisions of basic angle: -9999
Latitude of first grid point : 90.0
Longitude of first grid point : 0.0
Resolution & Component flags : 48
Winds : True
Latitude of last grid point : -90.0
Longitude of last grid point : 359.5
i direction increment : 0.5
j direction increment : 0.5
Grid Units : degrees
Scanning mode : 0
Product Definition : 2 Derived forecast on all ensemble members at a point in time
Parameter Category : 2 Momentum
Parameter Name : 1 Wind_speed
Parameter Units : m s-1
Generating Process Type : 4 Ensemble Forecast
ForecastTime : 24
First Surface Type : 100 Isobaric surface
First Surface value : 85000.0
Second Surface Type : 255 Missing
Second Surface value : -9.999E-252
======= Grib2ExtractRawData ==========
finished
I tried around for two days now but couldn't get it to work! I can't obtain the content data (lat, lon, value) from the file...
Can someone give an example in Java?
You shouldn't use the GRIB classes in netCDF-java directly. Instead, use
NetcdfFile.open()
That will give you access through the CDM, giving you a straightforward interface with variables and attributes. There's a tutorial here: https://www.unidata.ucar.edu/software/thredds/current/netcdf-java/tutorial/NetcdfFile.html
Is there a way to get all html5tags with one command instead of doing this? :
int h = (doc.getElementsByTag("canvas").size()
+ doc.getElementsByTag("audio").size()
+ doc.getElementsByTag("embed").size()
+ doc.getElementsByTag("source").size()
etc.
You can achieve the same result in one command using the select() method. This method allows you to specify multiple selectors, and Jsoup will return unique elements from the document that match any of the specified selectors.
For example:
int h = doc.select("canvas, audio, embed, source").size();
You can add as many comma-separated arguments as you need (e.g. all of the new elements introduced in HTML5).
Here you are :
all_html5_tags = [ '!DOCTYPE' ,'a' ,'abbr' ,'acronym' ,'address' ,'applet' ,'area' ,'article' ,'aside' ,'audio' ,'b' ,'base' ,'basefont' ,'bdi' ,'bdo' ,'big' ,'blockquote' ,'body' ,'br' ,'button' ,'canvas' ,'caption' ,'center' ,'cite' ,'code' ,'col' ,'colgroup' ,'command' ,'datalist' ,'dd' ,'del' ,'details' ,'dfn' ,'dir' ,'div' ,'dl' ,'dt' ,'em' ,'embed' ,'fieldset' ,'figcaption' ,'figure' ,'font' ,'footer' ,'form' ,'frame' ,'frameset' ,'h1' ,'h2' ,'h3' ,'h4' ,'h5' ,'h6' ,'head' ,'header' ,'hgroup' ,'hr' ,'html' ,'i' ,'iframe' ,'img' ,'input' ,'ins' ,'kbd' ,'keygen' ,'label' ,'legend' ,'li' ,'link' ,'map' ,'mark' ,'menu' ,'meta' ,'meter' ,'nav' ,'noframes' ,'noscript' ,'object' ,'ol' ,'optgroup' ,'option' ,'output' ,'p' ,'param' ,'pre' ,'progress' ,'q' ,'rp' ,'rt' ,'ruby' ,'s' ,'samp' ,'script' ,'section' ,'select' ,'small' ,'source' ,'span' ,'strike' ,'strong' ,'style' ,'sub' ,'summary' ,'sup' ,'table' ,'tbody' ,'td' ,'textarea' ,'tfoot' ,'th' ,'thead' ,'time' ,'title' ,'tr' ,'track' ,'tt' ,'u' ,'ul' ,'var' ,'video' ,'wbr' ]
I have a desktop java application (java 1.4.2), that needs to determine the information regarding two screens on linux environment:
# cat /etc/redhat-release
Red Hat Enterprise Linux WS release 4 (Nahant Update 7)
# lsb_release
cat /proc/versionLSB Version:
:core-3.0-ia32:core-3.0-noarch:graphics-3.0-ia32:graphics-3.0-noarch
# cat /proc/version
Linux version 2.6.9-78.ELsmp (brewbuilder#hs20-bc2-3.build.redhat.com)
(gcc version 3.4.6 20060404 (Red Hat 3.4.6-10)) #1 SMP Wed Jul 9 15:39:47 EDT 2008
and the screens are 2048x2048 and 1600x1200.
The code is
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] allScreens = env.getScreenDevices();
log("=============================================");
log("Total num. of screen = " + allScreens.length);
for (int i = 0; i < allScreens.length; i++) {
log("--------------------------------------");
log(
allScreens[i].getIDstring() + " width: " + allScreens[i].getDisplayMode().getWidth() +
" - height: " + allScreens[i].getDisplayMode().getHeight());
GraphicsConfiguration dgc =
allScreens[i].getDefaultConfiguration();
Rectangle bounds = dgc.getBounds();
Insets insets = Toolkit.getDefaultToolkit().getScreenInsets(dgc);
log("Bounds: " + bounds);
log("Insets: " + insets);
log("--------------------------------------");
}
log("=============================================");
but the output is
=============================================
Total num. of screen = 2
--------------------------------------
:0.0 width: 2048 - height: 2048
Bounds: java.awt.Rectangle[x=0,y=0,width=2048,height=2048]
Insets: java.awt.Insets[top=0,left=0,bottom=0,right=0]
--------------------------------------
--------------------------------------
:0.1 width: 2048 - height: 2048
Bounds: java.awt.Rectangle[x=0,y=0,width=1600,height=1200]
Insets: java.awt.Insets[top=0,left=0,bottom=0,right=0]
--------------------------------------
=============================================
the screen :0.1 is 2048x2048 when using allScreens[i].getDisplayMode(), and is 1600x1200 when using getDefaultConfiguration().getBounds():
why I have different results ?
The API code for getDisplayMode() is
public DisplayMode getDisplayMode() {
GraphicsConfiguration gc = getDefaultConfiguration();
Rectangle r = gc.getBounds();
ColorModel cm = gc.getColorModel();
return new DisplayMode(r.width, r.height, cm.getPixelSize(), 0);
}
so the values should be the same: why are different ?
Thanks
That is something I also noticed on my own application which requires the front gui to fit in to different monitors in a multi-monitor environment. The problem is something related to the video card, an Intel video card will present you the same width and height for different monitors, basically the primary's, if you use allScreens[i].getDisplayMode(), whereas the NVidia and ATI(AMD) ones give you the actual resolution values corresponding to each monitor using the same function.
So the proper way to get the right resolution for each monitor in a multiple-monitor environments regardless of video card is to use getDefaultConfiguration().getBounds().width or height.
Hope it helps.