Add a watermark with Apache POI to a docx that already have a header - apache-poi

How can I add a watermark to a docx file that already have a header.
All the examples code show how to add to a doc with an empty header, but if the document already have one, the code fail.
The main issue is in XWPFHeaderFooterPolicy.createHeader(..) because it ignore the call if a header exist, so the paragraph with the watermark info is not added.
public XWPFHeader createHeader(Enum type, XWPFParagraph[] pars) {
XWPFHeader header = getHeader(type);
if (header == null) {
HdrDocument hdrDoc = HdrDocument.Factory.newInstance();
XWPFRelation relation = XWPFRelation.HEADER;
int i = getRelationIndex(relation);
XWPFHeader wrapper = (XWPFHeader) doc.createRelationship(relation,
XWPFFactory.getInstance(), i);
wrapper.setXWPFDocument(doc);
CTHdrFtr hdr = buildHdr(type, wrapper, pars);
wrapper.setHeaderFooter(hdr);
hdrDoc.setHdr(hdr);
assignHeader(wrapper, type);
header = wrapper;
}
return header;
}
When createWatermark call that method, it simply enter and out doing nothing.
I do not found a way to do the same. How could I correct this?

The XWPFHeaderFooterPolicy.createHeader is only used to create new headers. If headers are already present, then nothing will be changed in those headers.
If you look into the source code of XWPFHeaderFooterPolicy, as you had done already, you will see that the watermark simply is a WordArt shape within a paragraph in the header. So you simply could create that kind of WordArt shape in a already existant paragraph in a header. To do so try to understand XWPFHeaderFooterPolicy.getWatermarkParagraph(String text, int idx) and rewrite it into a setWatermarkInParagraph(XWPFParagraph paragraph, String text). Then you can get or create a paragraph in any header you want and put the watermark into that paragraph.
Following complete example shows this. It works using apache poi 5.0.0. Using apache poi 3.17 or apache poi 4.1.2 the commented changes in import statements need to be done.
import java.io.*;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.wp.usermodel.HeaderFooterType;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;
import com.microsoft.schemas.office.office.*;
import com.microsoft.schemas.office.office.CTLock;
import com.microsoft.schemas.vml.*;
import org.openxmlformats.schemas.officeDocument.x2006.sharedTypes.STTrueFalse; // apache ppi 5.0.0
//import com.microsoft.schemas.vml.STTrueFalse; // apache poi 3.17 and apache poi 4.1.2
public class CreateWordHeaderWatermarkInExistingDocument {
private static void setWatermarkInParagraph(XWPFParagraph paragraph, String text) {
//CTP p = CTP.Factory.newInstance();
CTP p = paragraph.getCTP();
XWPFDocument doc = paragraph.getDocument();
CTBody ctBody = doc.getDocument().getBody();
byte[] rsidr = null;
byte[] rsidrdefault = null;
if (ctBody.sizeOfPArray() == 0) {
// TODO generate rsidr and rsidrdefault
} else {
CTP ctp = ctBody.getPArray(0);
rsidr = ctp.getRsidR();
rsidrdefault = ctp.getRsidRDefault();
}
p.setRsidP(rsidr);
p.setRsidRDefault(rsidrdefault);
CTPPr pPr = p.getPPr(); if (pPr == null) pPr = p.addNewPPr();
CTString pStyle = pPr.getPStyle(); if (pStyle == null) pStyle = pPr.addNewPStyle();
pStyle.setVal("Header");
// start watermark paragraph
CTR r = p.addNewR();
CTRPr rPr = r.addNewRPr();
rPr.addNewNoProof();
int idx = 1;
CTPicture pict = r.addNewPict();
CTGroup group = CTGroup.Factory.newInstance();
CTShapetype shapetype = group.addNewShapetype();
shapetype.setId("_x0000_t136");
shapetype.setCoordsize("1600,21600");
shapetype.setSpt(136);
shapetype.setAdj("10800");
shapetype.setPath2("m#7,0l#8,0m#5,21600l#6,21600e");
CTFormulas formulas = shapetype.addNewFormulas();
formulas.addNewF().setEqn("sum #0 0 10800");
formulas.addNewF().setEqn("prod #0 2 1");
formulas.addNewF().setEqn("sum 21600 0 #1");
formulas.addNewF().setEqn("sum 0 0 #2");
formulas.addNewF().setEqn("sum 21600 0 #3");
formulas.addNewF().setEqn("if #0 #3 0");
formulas.addNewF().setEqn("if #0 21600 #1");
formulas.addNewF().setEqn("if #0 0 #2");
formulas.addNewF().setEqn("if #0 #4 21600");
formulas.addNewF().setEqn("mid #5 #6");
formulas.addNewF().setEqn("mid #8 #5");
formulas.addNewF().setEqn("mid #7 #8");
formulas.addNewF().setEqn("mid #6 #7");
formulas.addNewF().setEqn("sum #6 0 #5");
CTPath path = shapetype.addNewPath();
path.setTextpathok(STTrueFalse.T);
path.setConnecttype(STConnectType.CUSTOM);
path.setConnectlocs("#9,0;#10,10800;#11,21600;#12,10800");
path.setConnectangles("270,180,90,0");
CTTextPath shapeTypeTextPath = shapetype.addNewTextpath();
shapeTypeTextPath.setOn(STTrueFalse.T);
shapeTypeTextPath.setFitshape(STTrueFalse.T);
CTHandles handles = shapetype.addNewHandles();
CTH h = handles.addNewH();
h.setPosition("#0,bottomRight");
h.setXrange("6629,14971");
CTLock lock = shapetype.addNewLock();
lock.setExt(STExt.EDIT);
CTShape shape = group.addNewShape();
shape.setId("PowerPlusWaterMarkObject" + idx);
shape.setSpid("_x0000_s102" + (4 + idx));
shape.setType("#_x0000_t136");
shape.setStyle("position:absolute;margin-left:0;margin-top:0;width:415pt;height:207.5pt;z-index:-251654144;mso-wrap-edited:f;mso-position-horizontal:center;mso-position-horizontal-relative:margin;mso-position-vertical:center;mso-position-vertical-relative:margin");
shape.setWrapcoords("616 5068 390 16297 39 16921 -39 17155 7265 17545 7186 17467 -39 17467 18904 17467 10507 17467 8710 17545 18904 17077 18787 16843 18358 16297 18279 12554 19178 12476 20701 11774 20779 11228 21131 10059 21248 8811 21248 7563 20975 6316 20935 5380 19490 5146 14022 5068 2616 5068");
shape.setFillcolor("#d8d8d8");
shape.setStyle(shape.getStyle() + ";rotation:315");
shape.setStroked(STTrueFalse.FALSE);
CTTextPath shapeTextPath = shape.addNewTextpath();
shapeTextPath.setStyle("font-family:"Cambria";font-size:1pt");
shapeTextPath.setString(text);
pict.set(group);
}
public static void main(String[] args) throws Exception {
//XWPFDocument doc= new XWPFDocument();
XWPFDocument doc= new XWPFDocument(new FileInputStream("./WordDocument.docx"));
// the body content
XWPFParagraph paragraph = doc.createParagraph();
XWPFRun run=paragraph.createRun();
run.setText("New text in body.");
// get or create the default header
XWPFHeader header = doc.createHeader(HeaderFooterType.DEFAULT);
// get or create first paragraph in first header
paragraph = header.getParagraphArray(0);
if (paragraph == null) paragraph = header.createParagraph();
// set watermark to that paragraph
setWatermarkInParagraph(paragraph, "Watermark default");
header = doc.createHeader(HeaderFooterType.EVEN);
paragraph = header.getParagraphArray(0);
if (paragraph == null) paragraph = header.createParagraph();
setWatermarkInParagraph(paragraph, "Watermark even");
header = doc.createHeader(HeaderFooterType.FIRST);
paragraph = header.getParagraphArray(0);
if (paragraph == null) paragraph = header.createParagraph();
setWatermarkInParagraph(paragraph, "Watermark first");
FileOutputStream out = new FileOutputStream("./WordDocumentWithWatermark.docx");
doc.write(out);
out.close();
doc.close();
}
}

Based on the excellent answer of Axel I wrote this code:
public DocumentTools addWatermark(String watermark) throws IOException {
addWatermark(watermark, "#d8d8d8", 315, HeaderFooterType.DEFAULT);
return this;
}
public DocumentTools addWatermark(String watermark, String color, float rotation, HeaderFooterType... hft) throws IOException {
if (hft.length == 0) {
hft = new HeaderFooterType[1];
hft[0] = HeaderFooterType.DEFAULT;
}
for (HeaderFooterType headerFooterType : hft) {
// get or create the default header
XWPFHeader header = doc.createHeader(headerFooterType);
// get or create first paragraph in first header
XWPFParagraph paragraph = header.getParagraphArray(0);
if (paragraph == null) {
paragraph = header.createParagraph();
}
// set watermark to that paragraph
setWatermarkInParagraph(paragraph, watermark, color, rotation);
}
return this;
}
//=====================================================
// Axel code with a minimal fix for color and rotation parameters.
//=====================================================
private static void setWatermarkInParagraph(XWPFParagraph paragraph, String text, String color, float rotation) {
//CTP p = CTP.Factory.newInstance();
CTP p = paragraph.getCTP();
XWPFDocument doc = paragraph.getDocument();
CTBody ctBody = doc.getDocument().getBody();
byte[] rsidr = null;
byte[] rsidrdefault = null;
if (ctBody.sizeOfPArray() == 0) {
// TODO generate rsidr and rsidrdefault
} else {
CTP ctp = ctBody.getPArray(0);
rsidr = ctp.getRsidR();
rsidrdefault = ctp.getRsidRDefault();
}
p.setRsidP(rsidr);
p.setRsidRDefault(rsidrdefault);
CTPPr pPr = p.getPPr();
if (pPr == null) {
pPr = p.addNewPPr();
}
CTString pStyle = pPr.getPStyle();
if (pStyle == null) {
pStyle = pPr.addNewPStyle();
}
pStyle.setVal("Header");
// start watermark paragraph
CTR r = p.addNewR();
CTRPr rPr = r.addNewRPr();
rPr.addNewNoProof();
int idx = 1;
CTPicture pict = r.addNewPict();
CTGroup group = CTGroup.Factory.newInstance();
CTShapetype shapetype = group.addNewShapetype();
shapetype.setId("_x0000_t136");
shapetype.setCoordsize("1600,21600");
shapetype.setSpt(136);
shapetype.setAdj("10800");
shapetype.setPath2("m#7,0l#8,0m#5,21600l#6,21600e");
CTFormulas formulas = shapetype.addNewFormulas();
formulas.addNewF().setEqn("sum #0 0 10800");
formulas.addNewF().setEqn("prod #0 2 1");
formulas.addNewF().setEqn("sum 21600 0 #1");
formulas.addNewF().setEqn("sum 0 0 #2");
formulas.addNewF().setEqn("sum 21600 0 #3");
formulas.addNewF().setEqn("if #0 #3 0");
formulas.addNewF().setEqn("if #0 21600 #1");
formulas.addNewF().setEqn("if #0 0 #2");
formulas.addNewF().setEqn("if #0 #4 21600");
formulas.addNewF().setEqn("mid #5 #6");
formulas.addNewF().setEqn("mid #8 #5");
formulas.addNewF().setEqn("mid #7 #8");
formulas.addNewF().setEqn("mid #6 #7");
formulas.addNewF().setEqn("sum #6 0 #5");
CTPath path = shapetype.addNewPath();
path.setTextpathok(STTrueFalse.T);
path.setConnecttype(STConnectType.CUSTOM);
path.setConnectlocs("#9,0;#10,10800;#11,21600;#12,10800");
path.setConnectangles("270,180,90,0");
CTTextPath shapeTypeTextPath = shapetype.addNewTextpath();
shapeTypeTextPath.setOn(STTrueFalse.T);
shapeTypeTextPath.setFitshape(STTrueFalse.T);
CTHandles handles = shapetype.addNewHandles();
CTH h = handles.addNewH();
h.setPosition("#0,bottomRight");
h.setXrange("6629,14971");
CTLock lock = shapetype.addNewLock();
lock.setExt(STExt.EDIT);
CTShape shape = group.addNewShape();
shape.setId("PowerPlusWaterMarkObject" + idx);
shape.setSpid("_x0000_s102" + (4 + idx));
shape.setType("#_x0000_t136");
shape.setStyle("position:absolute;margin-left:0;margin-top:0;width:415pt;height:207.5pt;z-index:-251654144;mso-wrap-edited:f;mso-position-horizontal:center;mso-position-horizontal-relative:margin;mso-position-vertical:center;mso-position-vertical-relative:margin");
shape.setWrapcoords("616 5068 390 16297 39 16921 -39 17155 7265 17545 7186 17467 -39 17467 18904 17467 10507 17467 8710 17545 18904 17077 18787 16843 18358 16297 18279 12554 19178 12476 20701 11774 20779 11228 21131 10059 21248 8811 21248 7563 20975 6316 20935 5380 19490 5146 14022 5068 2616 5068");
shape.setFillcolor(color);
shape.setStyle(shape.getStyle() + ";rotation:"+rotation);
shape.setStroked(STTrueFalse.FALSE);
CTTextPath shapeTextPath = shape.addNewTextpath();
shapeTextPath.setStyle("font-family:"Cambria";font-size:1pt");
shapeTextPath.setString(text);
pict.set(group);
}

Related

App behaves differently on different devices

enter image description here
enter image description here
I created an App and when I run it on a Motorola Xoom it executes the main activity as I expected but when I run it on a Huawei phone it displays Hello World and never executes the main activity. (Android 4.1.2 and 8 respectively. I have created projects using the Basic Activity and the Empty Activity and get the same result with both). How do I stop the Hello World?
package com.example.xoom;
import android.hardware.usb.UsbConstants;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.app.PendingIntent;
import android.content.Intent;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Button;
import android.content.Context;
import android.hardware.usb.UsbManager;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.graphics.Color;
import android.graphics.Typeface;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity
{
final Button[] pitchButton = new Button[50];
int startLength;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String ACTION_USB_PERMISSION = "com.example.xoom";
byte[] sendChar = {0x5A}; // ASCII "Z"
byte[] getChar = new byte[200];
boolean addListener;
TextView tv = new TextView(this);
int buttonCount = 0;
for (int i = 0; i < 50; i++)
{
pitchButton[i] = new Button(this);
pitchButton[i].setTypeface(Typeface.MONOSPACE);
}
tv.setTextSize(20);
getWindow().getDecorView().setBackgroundColor(Color.CYAN);
UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
if (manager.getDeviceList().isEmpty()) // The device list is empty
{
tv.setTextColor(Color.RED);
tv.append("No USB Devices Found");
}
else
{
tv.setTextColor(Color.BLUE);
HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
UsbDevice device = deviceIterator.next(); // Get first device in list
PendingIntent pi = PendingIntent.getBroadcast(this, 0,
new Intent(ACTION_USB_PERMISSION), 0);
manager.requestPermission(device, pi);
UsbDeviceConnection connection = manager.openDevice(device);
getDeviceProperties(device, manager, tv); // Show USB device properties
getInterfaceProperties(device, connection, tv); // Show USB Interface properties
tv.setText(""); // Clear information from above because you don't want to see
// it normally but sometimes you do. Make this statement
// a comment if you do.
setConnectionProperties(connection); // Set speed etc of connection
UsbEndpoint endpointOut = device.getInterface(1).getEndpoint(1);
UsbEndpoint endpointIn = device.getInterface(1).getEndpoint(0);
connection.bulkTransfer(endpointOut, sendChar, 1, 500); // Send request for data
//
// It takes more than one read to get the data out of the FIFO
// Build up message by polling the FIFO until there is nothing left
// This has taken a lot of fiddling about to make it work. The baud
// and the timeouts have to be just so.
// (9600 and 200 work here but why who knows (or cares))
//
int k = 0;
char[] labelStr = new char[20];
int flag = Spanned.SPAN_EXCLUSIVE_EXCLUSIVE;
int bytesReceived = connection.bulkTransfer(endpointIn, getChar, 200, 200);
while (bytesReceived > 0)
{
for (int j = 0; j < bytesReceived; j++)
{
labelStr[k++] = (char) getChar[j];
if (getChar[j] == 13) // Carriage return
{
String label = String.valueOf(labelStr, 1, k - 1);
SpannableString spanLabel = new SpannableString(label);
spanLabel.setSpan(new RelativeSizeSpan(1.0f), 0, spanLabel.length(), flag);
addListener = true;
if (label.contains("Cross Slide"))
{ // Start adding pitches
spanLabel = new SpannableString("Pitch");
spanLabel.setSpan(new ForegroundColorSpan(Color.RED), 0, spanLabel.length(), flag);
addListener = false;
}
if (label.contains("End"))
{ // Start adding lengths
spanLabel = new SpannableString("Length");
spanLabel.setSpan(new ForegroundColorSpan(Color.RED), 0, spanLabel.length(), flag);
addListener = false;
if (startLength == 0) // Avoid the second "End" messages from MCU
startLength = buttonCount;
}
pitchButton[buttonCount].setText(spanLabel);
pitchButton[buttonCount].setId(buttonCount);
if (addListener)
{
pitchButton[buttonCount].setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
int buttonIndex;
Button buttonText = (Button) v;
String bt = buttonText.getText().toString();
String message;
if (bt.contains(".")) // On Button press display selected value
{
message = "Pitch ";
buttonIndex = 0;
}
else
{
message = "Length ";
buttonIndex = startLength;
}
message = message + bt;
pitchButton[buttonIndex].setText(message);
pitchButton[buttonIndex].setBackgroundColor(Color.GREEN);
}
});
}
buttonCount++;
k = 0;
}
}
bytesReceived = connection.bulkTransfer(endpointIn, getChar, 200, 200);
}
connection.close();
RelativeLayout.LayoutParams[] params = new RelativeLayout.LayoutParams[100];
RelativeLayout rel = new RelativeLayout(this);
rel.addView(tv);
int leftMargin = 0;
int topMargin = 0;
int lineCount = 0;
for (int i = 0; i < buttonCount - 1; i++)
{
params[i] = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params[i].width = 150;
params[i].height = 50;
if (Math.IEEEremainder(lineCount, 5) == 0) // Put 5 buttons per line
{
topMargin = topMargin + params[i].height;
leftMargin = 0;
}
lineCount++;
if (pitchButton[i].getText().toString().contains("Pitch"))
{
topMargin = topMargin + params[i].height;
leftMargin = 0;
lineCount = 0;
}
if (pitchButton[i].getText().toString().contains("Length"))
{
topMargin = topMargin + params[i].height;
leftMargin = 0;
lineCount = 0;
}
params[i].leftMargin = leftMargin;
leftMargin = leftMargin + params[i].width;
params[i].topMargin = topMargin;
pitchButton[i].setLayoutParams(params[i]);
rel.addView(pitchButton[i]);
}
//
//Add control for setting taper
//
ArrayList<String> taperArray = new ArrayList<String>();
taperArray.add("1");
taperArray.add("2");
taperArray.add("3");
Spinner spinner = new Spinner(this,Spinner.MODE_DIALOG);
spinner.setBackgroundColor(Color.BLUE);
String taperPrompt = "Set Taper Angle";
RelativeLayout.LayoutParams spinnerParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
spinnerParams.width = 50;
spinnerParams.height = 40;
spinnerParams.topMargin = 600;
spinnerParams.leftMargin = 200;
spinner.setPrompt("Select Taper Angle");
spinner.setLayoutParams(spinnerParams);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, taperArray);
spinner.setAdapter(spinnerArrayAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l)
{
}
public void onNothingSelected(AdapterView<?> adapterView)
{
}
});
RelativeLayout.LayoutParams taperParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
taperParams.width = 200;
taperParams.height = 50;
taperParams.topMargin = 600;
taperParams.leftMargin = 10;
TextView taperView = new TextView(this);
taperView.setLayoutParams(taperParams);
taperView.setText(taperPrompt);
taperView.setTextColor(Color.RED);
taperView.setTextSize(20);
rel.addView(taperView);
rel.addView(spinner);
setContentView(rel);
}
}
public void setConnectionProperties(UsbDeviceConnection connection)
{
connection.controlTransfer(0x40, 0, 0, 0, null, 0, 0);// reset
// mConnection.controlTransfer(0×40,
// 0, 1, 0, null, 0,
// 0);//clear Rx
connection.controlTransfer(0x40, 0, 2, 0, null, 0, 0);// clear Tx
connection.controlTransfer(0x40, 0x02, 0x0000, 0, null, 0, 0);// flow
// control
// none
connection.controlTransfer(0x40, 0x03, 0x4138, 0, null, 0, 0);// baudrate
// 9600 (4138 is 9600, 1A is 115200 0271 is 4800)
connection.controlTransfer(0x40, 0x04, 0x0008, 0, null, 0, 0);// data bit
// 8, parity
// none,
// stop bit
// 1, tx off
}
public void getInterfaceProperties(UsbDevice device, UsbDeviceConnection connection, TextView tv)
{
int interfaceCount = device.getInterfaceCount();
int endPointCount;
for (int i=0; i < interfaceCount-1; i++)
{
if (connection.claimInterface(device.getInterface(i), true)) {
tv.append("\nConnection Interface " + i + " Claim succeeded \n");
UsbInterface interfce = device.getInterface(i);
endPointCount = interfce.getEndpointCount();
tv.append("Endpoint count for Interface " + i + " is " + endPointCount + "\n");
for (int j = 0; j < endPointCount; j++) {
if (interfce.getEndpoint(j).getType() == UsbConstants.USB_ENDPOINT_XFER_INT)
tv.append("Endpoint " + j + " Type is Xfer Int \n");
if (interfce.getEndpoint(j).getType() == UsbConstants.USB_ENDPOINT_XFER_BULK)
tv.append("Endpoint " + j + " Type is Bulk Xfer \n");
if (interfce.getEndpoint(j).getDirection() == UsbConstants.USB_DIR_IN)
tv.append("Endpoint " + j + " Direction is IN \n");
if (interfce.getEndpoint(j).getDirection() == UsbConstants.USB_DIR_OUT)
tv.append("Endpoint " + j + " Direction is OUT \n");
tv.append("Max packet size = " + interfce.getEndpoint(j).getMaxPacketSize() + "\n");
}
tv.append("Interface Protocol is " + interfce.getInterfaceProtocol() + "\n");
}
}
}
public void getDeviceProperties(UsbDevice device, UsbManager manager, TextView tv)
{
tv.setTextSize(20);
tv.setTextColor(Color.BLUE);
tv.append("USB Device name = " + device.getDeviceName() + "\n");
tv.append("USB Product Id = " + device.getProductId() + "\n");
tv.append("USB Vendor Id = " + device.getVendorId() + "\n");
tv.append("USB Device Id = " + device.getDeviceId() + "\n");
if (manager.hasPermission(device)) // Can the App access the device ?
{
tv.append("Device Permission = Yes \n");
}
else
{
tv.append("Device Permission = No \n");
}
}
}
I have found the answer – when no USB devices are attached to the phone the message No USB Devices Found could ever be displayed on the screen. By adding the line setContentView(tv) after the line tv.append(“No USB Devices Found”) leaves this message on the screen rather than falling back to the Hello World message. Thank you for looking at it. I would still like to know if it is possible to get rid of the Hello World fragment as it seems totally unnecessary (or maybe it is).

Need to reduce the spaces between 2 cells in apache poi word

I am trying to build a table. I need the space between 2 rows to be reduced but I am not able to achieve the result using row.setheight().
Below is the code :
import eu.europa.ec.fisheries.quotaprepservice.constants.StrConstants;
import eu.europa.ec.fisheries.quotaprepservice.report.bean.Annexe1ATacBeanQuotaItem;
import eu.europa.ec.fisheries.quotaprepservice.report.bean.TacBean;
import org.apache.logging.log4j.util.Strings;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.xmlbeans.impl.xb.xmlschema.SpaceAttribute;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.List;
import static eu.europa.ec.fisheries.quotaprepservice.constants.StrConstants.*;
public class WordBuilder1 {
public static void main(String[] args) throws Exception {
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText("The table:");
XWPFTable table = document.createTable(4, 8);
prepareQuotaList(table);
CTSectPr sectPr = document.getDocument().getBody().getSectPr();
if (sectPr == null) sectPr = document.getDocument().getBody().addNewSectPr();
CTPageSz pageSz = sectPr.addNewPgSz();
pageSz.setOrient(STPageOrientation.PORTRAIT);
pageSz.setW(BigInteger.valueOf(11900)); //12240 Twips = 12240/20 = 612 pt = 612/72 = 8.5"
pageSz.setH(BigInteger.valueOf(16840)); //15840 Twips = 15840/20 = 792 pt = 792/72 = 11"
FileOutputStream out = new FileOutputStream("C:\\Users\\mishrne\\example.docx");
document.write(out);
out.close();
}
private static void prepareQuotaList(XWPFTable table) {
int count = 0;
for (int row = 0; row < 4; row++) {
XWPFTableRow tableRow = table.getRow(row);
tableRow.setHeight((short) 0);
for (int col = 0; col < 3; col++) {
setCellBorders(tableRow.getCell(col), new STBorder.Enum[]{STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.NIL});
}
setCellBorders(tableRow.getCell(3), new STBorder.Enum[]{STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.NIL});
setCellBorders(tableRow.getCell(4), new STBorder.Enum[]{STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.NIL});
for (int col = 5; col < 8; col++) {
setCellBorders(tableRow.getCell(col), new STBorder.Enum[]{STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.NIL});
}
if (count == 2) {
createCell(tableRow.getCell(0), TAC, ParagraphAlignment.LEFT, 9);
createCell(tableRow.getCell(2), "80", "(2)", ParagraphAlignment.RIGHT);
} else {
createCell(tableRow.getCell(0), "Belgium", ParagraphAlignment.LEFT, 9);
mergeCellHorizontally(table, row, 2, 3);
createCell(tableRow.getCell(2), "80", "(2)", ParagraphAlignment.RIGHT);
}
count++;
}
}
private static void createCell(XWPFTableCell cell, String text, ParagraphAlignment paragraphAlignment, int fontSize) {
XWPFParagraph paragraph = (cell.getParagraphs().size() > 0) ? cell.getParagraphs().get(0) : cell.addParagraph();
paragraph.setIndentationLeft(5 * 20); // 10pt left indentation
paragraph.setAlignment(paragraphAlignment);
paragraph.setWordWrapped(true);
XWPFRun run = (paragraph.getRuns().size() > 0) ? paragraph.getRuns().get(0) : paragraph.createRun();
run.setText(text);
run.setFontFamily(TIMES_NEW_ROMAN);
run.setFontSize(fontSize);
cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
}
private static void createCell(XWPFTableCell cell, String text, String superscriptText, ParagraphAlignment left) {
XWPFRun run;
XWPFParagraph paragraph = (cell.getParagraphs().size() > 0) ? cell.getParagraphs().get(0) : cell.addParagraph();
paragraph.setIndentationLeft(5 * 20); // 10pt left indentation
paragraph.setAlignment(ParagraphAlignment.LEFT);
paragraph.setSpacingBefore(0);
paragraph.setSpacingBeforeLines(0);
run = (paragraph.getRuns().size() > 0) ? paragraph.getRuns().get(0) : paragraph.createRun();
run.setFontFamily(TIMES_NEW_ROMAN);
cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
run.setFontSize(9);
run.setText(text);
run = paragraph.createRun();
run.setText(StrConstants.BLANK_SPACE + StrConstants.BLANK_SPACE + StrConstants.BLANK_SPACE + superscriptText);
run.setFontSize(9);
run.setFontFamily(TIMES_NEW_ROMAN);
run.setSubscript(VerticalAlign.SUPERSCRIPT); // superscript (2)
}
private static void mergeCellHorizontally(XWPFTable table, int row, int fromCol, int toCol) {
XWPFTableCell cell = table.getRow(row).getCell(fromCol);
CTTcPr tcPr = cell.getCTTc().getTcPr();
if (tcPr == null) tcPr = cell.getCTTc().addNewTcPr();
if (tcPr.isSetGridSpan()) {
tcPr.getGridSpan().setVal(BigInteger.valueOf(toCol - fromCol + 1));
} else {
tcPr.addNewGridSpan().setVal(BigInteger.valueOf(toCol - fromCol + 1));
}
for (int colIndex = toCol; colIndex > fromCol; colIndex--) {
table.getRow(row).getCtRow().removeTc(colIndex);
table.getRow(row).removeCell(colIndex);
}
}
private static void setCellBorders(XWPFTableCell cell, STBorder.Enum[] borderTypesLTRB) {
CTTcBorders borders = CTTcBorders.Factory.newInstance();
borders.addNewLeft().setVal(borderTypesLTRB[0]);
borders.addNewTop().setVal(borderTypesLTRB[1]);
borders.addNewRight().setVal(borderTypesLTRB[2]);
borders.addNewBottom().setVal(borderTypesLTRB[3]);
CTTcPr tcPr = cell.getCTTc().getTcPr();
if (tcPr != null) {
tcPr.setTcBorders(borders);
} else {
tcPr = CTTcPr.Factory.newInstance();
tcPr.setTcBorders(borders);
cell.getCTTc().setTcPr(tcPr);
}
}
}
To set table row height in XWPFTable table the height rule also must be set additional to the height itself. For example:
table.getRow(0).setHeight(12*20); // row height in twentieth pt
table.getRow(0).getCtRow().getTrPr().getTrHeightArray(0).setHRule(STHeightRule.EXACT); // height rule exact
There are following height rules possible:
AT_LEAST: At least the given height. Higher if needed but not lesser.
AUTO: The default. Default height of one default paragraph height inclusive spacing before and after. As high as needed dependent on content.
EXACT: Exact the given height. Content possibly gets cut of.
Note, a 0 value for XWPFTableRow.setHeight will not be accepted in combination with EXACT height rule. This falls back to default AUTO height then.
According to your code sample:
...
private static void prepareQuotaList(XWPFTable table) {
int count = 0;
for (int row = 0; row < 4; row++) {
XWPFTableRow tableRow = table.getRow(row);
tableRow.setHeight(12*20); // row height = 12 pt
tableRow.getCtRow().getTrPr().getTrHeightArray(0).setHRule(STHeightRule.EXACT); // height rule exact
for (int col = 0; col < 3; col++) {
setCellBorders(tableRow.getCell(col), new STBorder.Enum[]{STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.NIL});
}
...
}
...
As said above there are only the three height rules possible. So if the goal is having table rows as high as their content but not more ore less, then height rule AUTO must be used. Then the paragraph's height determines the row height. Note a XWPFParagraph might have set spacing before, between and after the text rows. So you might have to set:
...
paragraph.setSpacingAfter(0);
paragraph.setSpacingBetween(1); // don't set this 0
paragraph.setSpacingBefore(0);
...
This must be set for each table cell which contains paragraphs already. So if needed for the whole table, then:
XWPFTable table = document.createTable(4, 8);
for (XWPFTableRow row : table.getRows()) {
for (XWPFTableCell cell : row.getTableCells()) {
for (XWPFParagraph p : cell.getParagraphs()) {
p.setSpacingAfter(0);
p.setSpacingBetween(1); // don't set this 0
p.setSpacingBefore(0);
}
}
}

Exception on downloading pdf from envelope

When i run this code.The Content is not allowed in prolog is coming.What is wroung in my code.
Here is code.
import java.io.*;
import java.net.URL;
import java.net.HttpURLConnection;
import javax.xml.xpath.*;
import org.xml.sax.InputSource;
import org.w3c.dom.*;
public class GetEnvelopeDoc
{
// Enter your info:
static String username = "*****";
static String password = "*****";
static String integratorKey = "******";
static String envelopeId = "**************";
static String envelopeUri = "/envelopes/" + envelopeId;
public static void main(String[] args) throws Exception
{
String url = "https://demo.docusign.net/restapi/v2/login_information";
String baseURL = ""; // we will retrieve this
String accountId = ""; // will retrieve
String authenticateStr =
"<DocuSignCredentials>" +
"<Username>" + username + "</Username>" +
"<Password>" + password + "</Password>" +
"<IntegratorKey>" + integratorKey + "</IntegratorKey>" +
"</DocuSignCredentials>";
//
// STEP 1 - Login
//
HttpURLConnection conn = (HttpURLConnection)new URL(url).openConnection();
conn.setRequestProperty("X-DocuSign-Authentication", authenticateStr);
conn.setRequestProperty("Content-Type", "application/xml");
conn.setRequestProperty("Accept", "application/xml");
int statusValue = conn.getResponseCode(); // side-effect of this call is to fire the request off
if( statusValue != 200 ) // 200 = OK
{
System.out.print("Error calling webservice, status is: " + statusValue);
System.exit(-1);
}
// we use xPath to get the baseUrl and accountId from the XML response body
BufferedReader br = new BufferedReader(new InputStreamReader( conn.getInputStream() ));
StringBuilder responseText = new StringBuilder(); String line = null;
while ( (line = br.readLine()) != null)
responseText.append(line);
String token1 = "//*[1]/*[local-name()='baseUrl']";
String token2 = "//*[1]/*[local-name()='accountId']";
XPath xPath = XPathFactory.newInstance().newXPath();
baseURL = xPath.evaluate(token1, new InputSource(new StringReader(responseText.toString())));
accountId = xPath.evaluate(token2, new InputSource(new StringReader(responseText.toString())));
//--- display results
System.out.println("baseUrl = " + baseURL + "\naccountId = " + accountId);
//
// STEP 2 - Get Info on Envelope's Document(s)
//
> conn = (HttpURLConnection)new URL(baseURL + envelopeUri +
> "/documents/combined").openConnection();
> conn.setRequestProperty("X-DocuSign-Authentication", authenticateStr);
> conn.setRequestProperty("Content-Type", "application/json");
> conn.setRequestProperty("Accept", "application/pdf");
> statusValue = conn.getResponseCode(); // triggers the request
if( statusValue != 200 )
{
System.out.println("Error calling webservice, status is: " + statusValue);
System.exit(-1);
}
// Read the response
InputStreamReader isr = new InputStreamReader(new DataInputStream( conn.getInputStream() ));
System.out.println(isr.toString());
br = new BufferedReader(isr);
StringBuilder response = new StringBuilder();
while ( (line = br.readLine()) != null)
response.append(line);
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile("//*[1]/*[local-name()='envelopeDocument']");
Object result = expr.evaluate(new InputSource(new StringReader(response.toString())), XPathConstants.NODESET);
//--- display results
System.out.println("\nDocument List -->");
int cnt = -1;
NodeList documents = (NodeList) result;
String[] docURIs = new String[documents.getLength()];
for (int i = 0; i < documents.getLength(); i++)
{
Node node = documents.item( i );
if (node != null && node.getNodeType() == Node.ELEMENT_NODE) {
NodeList docNodes = node.getChildNodes();
for (int j = 0; j < docNodes.getLength(); j++)
{
if( docNodes.item(j).getLocalName().equals("documentId"))
System.out.print("documentId: " + docNodes.item(j).getTextContent());
if( docNodes.item(j).getLocalName().equals("name"))
System.out.print(", name: " + docNodes.item(j).getTextContent());
if( docNodes.item(j).getLocalName().equals("uri"))
{
docURIs[++cnt] = docNodes.item(j).getTextContent(); // store the uris for later
System.out.print(", uri: " + docURIs[cnt]);
}
}
System.out.println();
}
}
//
// STEP 3 - Download the document(s)
//
for( int i = 0; i < docURIs.length; i++)
{
// append document uri to url for each document
conn = (HttpURLConnection)new URL(baseURL + docURIs[i]).openConnection();
conn.setRequestProperty("X-DocuSign-Authentication", authenticateStr);
statusValue = conn.getResponseCode();
if( statusValue != 200 )
{
System.out.println("Error calling webservice, status is: " + statusValue);
System.exit(-1);
}
// Grab the document data and write to a local file
isr = new InputStreamReader( conn.getInputStream() );
br = new BufferedReader(isr);
StringBuilder response2 = new StringBuilder();
while ( (line = br.readLine()) != null)
response2.append(line);
BufferedWriter out = new BufferedWriter(new FileWriter("document_" + i + ".pdf"));
out.write(response2.toString());
out.close();
}
System.out.println("\nDone downloading document(s)!");
}
}
Your question is not very clear, I don't know what you mean when you say "the content is not allowed in prolog", however it looks like you have some extra characters in your code. Was this part a copy-paste error? You have the > symbols in front of each of these lines.
> conn = (HttpURLConnection)new URL(baseURL + envelopeUri +
> "/documents/combined").openConnection();
> conn.setRequestProperty("X-DocuSign-Authentication", authenticateStr);
> conn.setRequestProperty("Content-Type", "application/json");
> conn.setRequestProperty("Accept", "application/pdf");
> statusValue = conn.getResponseCode(); // triggers the request

How can i refer to a textbox that i don't know it's name?

I'm using VC++ 2008 (Windows Form Application C++\CLR), I created dynamic array of textboxes (the user defines how many textboxes he wants to create), and i want to make a KeyPress event handler, in order to prevent Chars (i want these textboxes to be numerical only, and accept only one dot "for decimal numbers"). So how can I refer to the textbox that the user is using (the textbox that the cursor on for example) is there any way i can do this? The function looks like:
private: System::Void textBox_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e) {
if(e->KeyChar == '.')
{
if(this->/*the textbox in use*/->Text->Contains(".") && !this->/*the textbox in use*/->SelectedText->Contains("."))
e->Handled = true;
}
else if(!Char::IsDigit(e->KeyChar) && e->KeyChar != 0x08)
e->Handled = true;
}
private void CreateTextBoxControls()
{
intColCount= Convert.ToInt32(txtColumnNo.Text.ToString().Trim());
int rowCount =0;
Table tblHead = new Table();
if (tblHead.GetType().ToString().Equals("System.Web.UI.WebControls.Table") && PHOptions.FindControl("tblHead") == null )
{
tblHead.ID = "tblHead";
tblHead.EnableViewState = true;
tblHead.BorderWidth=Unit.Pixel(0);
tblHead.CellSpacing = 0;
tblHead.CellPadding = 1;
tblHead.Width = Unit.Percentage(96);
TableRow rH = new TableRow();
TableCell cH = new TableCell();
cH.Text= "Table Heading" ;
cH.Font.Bold = true;
rH.Cells.Add(cH);
tblHead.Rows.Add(rH);
PHOptions.Controls.Add(tblHead);
if(intColCount>0)
rH.Visible =true;
else
rH.Visible =false;
}
Table tblHelp = new Table();
if (tblHelp.GetType().ToString().Equals("System.Web.UI.WebControls.Table") && PHOptions.FindControl("tblHelp") == null )
{
tblHelp.ID = "tblHelp";
}
tblHelp.EnableViewState = true;
tblHelp.BorderWidth=Unit.Pixel(1);
tblHelp.CellSpacing = 0;
tblHelp.CellPadding = 1;
tblHelp.BorderWidth = Unit.Pixel(1);
tblHelp.Width = Unit.Percentage(96);
for (int rowIndex=0; rowIndex<=rowCount; rowIndex++)
{
TableRow r = new TableRow();
TableRow rWeight= new TableRow();
//r.ID = "rLabel";
TableRow rID = new TableRow();
for (int clIndex=0; clIndex<intColCount; clIndex++)
{
TableCell c = new TableCell();
txtBox = new TextBox();
if (txtBox.GetType().ToString().Equals("System.Web.UI.WebControls.TextBox") && PHOptions.FindControl("txtOption"+(clIndex+1).ToString()) == null )
{
txtBox.ID ="txtOption"+(clIndex+1).ToString();
//txtBox.Text = (clIndex+1).ToString();
txtBox.Width= Unit.Pixel(45);
txtBox.MaxLength = 2;
c.BorderWidth=Unit.Pixel(1);
c.Width=Unit.Pixel(80);
c.Controls.Add(txtBox);
r.Cells.Add(c);
txtBox.PreRender += new System.EventHandler(this.txtBox_PreRender);
}
}
tblHelp.Rows.Add(r);
}
TableRow rSubmit = new TableRow();
TableCell cSubmit = new TableCell();
cSubmit.ColumnSpan = intColCount ;
btnSubmitButton = new Button();
btnSubmitButton.ID ="btnSubmit";
btnSubmitButton.Text= "Submit";
if( PHOptions.FindControl("btnSubmit") == null )
cSubmit.Controls.Add(btnSubmitButton);
cSubmit.Attributes.Add("Align","Center");
rSubmit.Cells.Add(cSubmit);
tblHelp.Rows.Add(rSubmit);
PHOptions.Controls.Add(tblHelp);
this.btnSubmitButton.PreRender += new System.EventHandler(this.btnSubmitButton_PreRender);
this.btnSubmitButton.Click += new System.EventHandler(this.btnSubmitButton_Click);
}
private void btnSubmitButton_Click(object sender, System.EventArgs e)
{
for (int clIndex=0; clIndex<intColCount; clIndex++)
{
string boxName = "txtOption" + (clIndex+1).ToString();
TextBox tb = PHOptions.FindControl(boxName) as TextBox;
if( lblDisplay.Text != "" )
lblDisplay.Text+=","+tb.Text ;
else
lblDisplay.Text=tb.Text ;
}
}
Just refer this code ...
(this contains both for creating textbox dynamically and read from textbox)

how to extract Paragraph text color from ms word using apache poi

i am using apache POI , is it possible to read text background and foreground color from ms word paragraph
I got the solution
HWPFDocument doc = new HWPFDocument(fs);
WordExtractor we = new WordExtractor(doc);
Range range = doc.getRange();
String[] paragraphs = we.getParagraphText();
for (int i = 0; i < paragraphs.length; i++) {
org.apache.poi.hwpf.usermodel.Paragraph pr = range.getParagraph(i);
System.out.println(pr.getEndOffset());
int j=0;
while (true) {
CharacterRun run = pr.getCharacterRun(j++);
System.out.println("-------------------------------");
System.out.println("Color---"+ run.getColor());
System.out.println("getFontName---"+ run.getFontName());
System.out.println("getFontSize---"+ run.getFontSize());
if( run.getEndOffset()==pr.getEndOffset()){
break;
}
}
}
I found it in :
CharacterRun run = para.getCharacterRun(i)
i should be integer and should be incremented so the code will be as follow :
int c=0;
while (true) {
CharacterRun run = para.getCharacterRun(c++);
int x = run.getPicOffset();
System.out.println("pic offset" + x);
if (run.getEndOffset() == para.getEndOffset()) {
break;
}
}
if (paragraph != null)
{
int numberOfRuns = paragraph.NumCharacterRuns;
for (int runIndex = 0; runIndex < numberOfRuns; runIndex++)
{
CharacterRun run = paragraph.GetCharacterRun(runIndex);
string color = getColor24(run.GetIco24());
}
}
GetColor24 Function to Convert Color in Hex Format for C#
public static String getColor24(int argbValue)
{
if (argbValue == -1)
return "";
int bgrValue = argbValue & 0x00FFFFFF;
int rgbValue = (bgrValue & 0x0000FF) << 16 | (bgrValue & 0x00FF00)
| (bgrValue & 0xFF0000) >> 16;
StringBuilder result = new StringBuilder("#");
String hex = rgbValue.ToString("X");
for (int i = hex.Length; i < 6; i++)
{
result.Append('0');
}
result.Append(hex);
return result.ToString();
}
if you are working on docx(OOXML), you may want to take a look on this:
import java.io.*
import org.apache.poi.xwpf.usermodel.XWPFDocument
fun test(){
try {
val file = File("file.docx")
val fis = FileInputStream(file.absolutePath)
val document = XWPFDocument(fis)
val paragraphs = document.paragraphs
for (para in paragraphs) {
println("-- ("+para.alignment+") " + para.text)
para.runs.forEach { it ->
println(
"text:" + it.text() + " "
+ "(color:" + it.color
+ ",fontFamily:" + it.fontFamily
+ ")"
)
}
}
fis.close()
} catch (e: Exception) {
e.printStackTrace()
}
}

Resources