Skip to content

Instantly share code, notes, and snippets.

@StefanKruk
Created November 9, 2016 08:31
Show Gist options
  • Select an option

  • Save StefanKruk/544a5987de78ace77efbbee304012709 to your computer and use it in GitHub Desktop.

Select an option

Save StefanKruk/544a5987de78ace77efbbee304012709 to your computer and use it in GitHub Desktop.
Template für ein XWPFDocument Handler
package com.github.stefankruk.docx
import org.apache.poi.xwpf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* Handler-Klasse zum verwalten von XWPFDocument Objekten. Die Klasse soll dafür genutzt werden, um
* ein <b>.docx Dokument</b> zu bearbeiten.
*
*/
public class XWPFDocumentHandler
{
private static final Logger LOG = LoggerFactory.getLogger(XWPFDocumentHandler.class);
private final XWPFDocument doc;
/**
* Erzeugt eine neue Instanz.
*
* @param is
* @throws IOException
*/
public XWPFDocumentHandler(final InputStream is) throws IOException
{
doc = new XWPFDocument(is);
}
/**
* Gibt das {@link XWPFDocument} zurück
*
* @return doc
*/
public XWPFDocument getDoc()
{
return doc;
}
public byte[] getContent() throws IOException
{
byte[] result = null;
try (ByteArrayOutputStream out = new ByteArrayOutputStream())
{
doc.write(out);
result = out.toByteArray();
}
return result;
}
/**
* Ersetzt alle Variablen im Dokument mit den entsprechenden Werten.
*
* @param object
*/
public void replace(final Map<String,String> replacement)
{
replaceIntern(replacement);
replaceTable(replacement);
}
private void replaceIntern(final Map<String, String> replacements)
{
LOG.info("Ersetzte alle Variablen in Texten");
final List<XWPFParagraph> xwpfParagraphs = doc.getParagraphs();
for (final XWPFParagraph paragraph : xwpfParagraphs)
{
final List<XWPFRun> runs = paragraph.getRuns();
for (final Map.Entry<String, String> replPair : replacements.entrySet())
{
final String find = replPair.getKey();
final String repl = replPair.getValue();
final TextSegement found = paragraph.searchText(find, new PositionInParagraph());
if (found == null)
{
continue;
}
if (found.getBeginRun() == found.getEndRun())
{
// whole search string is in one Run
final XWPFRun run = runs.get(found.getBeginRun());
replaceText(run, find, repl);
}
else
{
// The search string spans over more than one Run
XWPFRun partOne = putRunsTogether(runs, found.getBeginRun(), found.getEndRun());
// The Text will be replaced.
replaceText(partOne, find, repl);
}
}
}
}
/**
* Setzt mehrere Runs zusammen
*
* @param runs
* @param foundStart
* @param foundEnd
* @return run
*/
private XWPFRun putRunsTogether(List<XWPFRun> runs, int foundStart, int foundEnd){
// The search string spans over more than one Run
// Put the Strings together
final StringBuilder b = new StringBuilder();
for (int runPos = foundStart; runPos <= foundEnd; runPos++)
{
final XWPFRun run = runs.get(runPos);
b.append(run.getText(run.getTextPosition()));
}
final String connectedRuns = b.toString();
// The first Run receives the String of all connected Runs
final XWPFRun partOne = runs.get(foundStart);
partOne.setText(connectedRuns, 0);
// Removing the text in the other Runs.
for (int runPos = foundStart + 1; runPos <= foundEnd; runPos++)
{
final XWPFRun partNext = runs.get(runPos);
partNext.setText("", 0);
}
return partOne;
}
private void replaceText(XWPFRun run, String find, String replace)
{
final String runText = run.getText(run.getTextPosition());
String replaced = runText.replace(find, replace);
if (runText.contains(find) && replaced.equals(runText))
{
// if nothing was replaced
}
if (replaced.contains("\n"))
{
String[] lines = replaced.split("\n");
run.setText(lines[0], 0); // set first line into XWPFRun
for (int i = 1; i < lines.length; i++)
{
// add break and insert new text
run.addBreak();
run.setText(lines[i]);
}
}
else
{
run.setText(replaced, 0);
}
}
/**
* Ersetzt alle Variablen in einer Tabelle mit den ensprechenden Werten.
*
* @param replacements
*/
private void replaceTable(final List<XWPFTableReplacements> replacements)
{
LOG.info("Ersetzte alle Tabellen Variablen");
final List<XWPFTable> tables = doc.getTables();
for (final XWPFTable t : tables)
{
final XWPFTableRow varRow = t.getRow(1);
final List<XWPFTableCell> varCells = varRow.getTableCells();
for (final XWPFTableReplacements tableRep : replacements)
{
final XWPFTableRow row = t.createRow();
final List<XWPFTableCell> cells = row.getTableCells();
final Map<String, String> rep = tableRep.getReplacements();
for (int i = 0; i < cells.size(); i++)
{
final String cellVarText = varCells.get(i).getText();
final XWPFTableCell cell = cells.get(i);
boolean replaced = false;
for (final Entry<String, String> r : rep.entrySet())
{
if (!cellVarText.contains(r.getKey()))
{
continue;
}
replaced = true;
final String repVar = cellVarText.replace(r.getKey(), r.getValue());
cell.setText(repVar);
break;
}
if (!replaced)
{
}
}
}
t.removeRow(1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment