Search in sources :

Example 1 with Chunk

use of com.itextpdf.text.Chunk in project motech by motech.

the class PdfTableWriter method writeCell.

private void writeCell(String column, String value) {
    // we want blank cells to display, even if they are the only ones
    Chunk chunk = StringUtils.isBlank(value) ? Chunk.NEWLINE : new Chunk(value);
    // add as a cell to the table
    PdfPCell cell = new PdfPCell(new Phrase(chunk));
    dataTable.addCell(cell);
    updateWidthIfNeeded(column, cell);
}
Also used : PdfPCell(com.itextpdf.text.pdf.PdfPCell) Phrase(com.itextpdf.text.Phrase) Chunk(com.itextpdf.text.Chunk)

Example 2 with Chunk

use of com.itextpdf.text.Chunk in project trainning by fernandotomasio.

the class DOC001PDF method buildTableDisciplina.

private PdfPTable buildTableDisciplina(DisciplinaDTO disciplina) throws DocumentException {
    PdfPTable table = new PdfPTable(6);
    table.setWidthPercentage(100);
    table.setExtendLastRow(true);
    PdfPCell cellCampo;
    Phrase phraseCampo = new Phrase();
    phraseCampo.add(new Chunk("CAMPO: ", fontManager.getBoldFont()));
    phraseCampo.add(new Chunk(disciplina.getCampo().getDescricao().toUpperCase(), fontManager.getDefaultFont()));
    cellCampo = new PdfPCell(phraseCampo);
    cellCampo.setPadding(10);
    cellCampo.setColspan(3);
    table.addCell(cellCampo);
    PdfPCell cellArea;
    Phrase phraseArea = new Phrase();
    phraseArea.add(new Chunk("ÁREA: ", fontManager.getBoldFont()));
    phraseArea.add(new Chunk(disciplina.getAreaEnsino().getNome().toUpperCase(), fontManager.getDefaultFont()));
    cellArea = new PdfPCell(phraseArea);
    cellArea.setColspan(3);
    cellArea.setPadding(10);
    table.addCell(cellArea);
    PdfPCell cellDescricao;
    Phrase phraseDescricao = new Phrase();
    phraseDescricao.add(new Chunk("DISCIPLINA " + disciplina.getNumeroDisciplina() + ": ", fontManager.getBoldFont()));
    phraseDescricao.add(new Chunk(disciplina.getDescricao().toUpperCase(), fontManager.getDefaultFont()));
    cellDescricao = new PdfPCell(phraseDescricao);
    cellDescricao.setColspan(6);
    cellDescricao.setPadding(10);
    table.addCell(cellDescricao);
    PdfPCell cellCHInstrucao;
    Phrase phraseCHInstrucao = new Phrase();
    phraseCHInstrucao.add(new Chunk("CH INSTR.: ", fontManager.getBoldFont()));
    phraseCHInstrucao.add(new Chunk(disciplina.getQuantidadeTemposAula() + " tempo(s)", fontManager.getDefaultFont()));
    cellCHInstrucao = new PdfPCell(phraseCHInstrucao);
    cellCHInstrucao.setColspan(2);
    cellCHInstrucao.setPadding(10);
    table.addCell(cellCHInstrucao);
    PdfPCell cellCHAvaliacao;
    Phrase phraseCHAvaliacao = new Phrase();
    phraseCHAvaliacao.add(new Chunk("CH AVAL.: ", fontManager.getBoldFont()));
    phraseCHAvaliacao.add(new Chunk(disciplina.getQuantidadeTemposAvaliacao() + " tempo(s)", fontManager.getDefaultFont()));
    cellCHAvaliacao = new PdfPCell(phraseCHAvaliacao);
    cellCHAvaliacao.setColspan(2);
    cellCHAvaliacao.setPadding(10);
    table.addCell(cellCHAvaliacao);
    PdfPCell cellCHTotal;
    Phrase phraseCHTotal = new Phrase();
    int quantidadeTempoTotal = disciplina.getQuantidadeTemposAula() + disciplina.getQuantidadeTemposAvaliacao();
    phraseCHTotal.add(new Chunk("CH TOTAL: ", fontManager.getBoldFont()));
    phraseCHTotal.add(new Chunk(quantidadeTempoTotal + " tempo(s)", fontManager.getDefaultFont()));
    cellCHTotal = new PdfPCell(phraseCHTotal);
    cellCHTotal.setColspan(2);
    cellCHTotal.setPadding(10);
    table.addCell(cellCHTotal);
    PdfPCell cellObjetivos;
    Paragraph objetivosHead = new Paragraph("OBJETIVOS ESPECÍFICOS: ", fontManager.getBoldFont());
    ObjetivoDisciplinaDTO[] objetivosDisciplina = teachingDocumentsService.findAllObjetivosDisciplinas(disciplina.getId());
    // Paragraph objetivos = new Paragraph("asdfasdfasdfasdf", fontManager.getDefaultFont());
    cellObjetivos = new PdfPCell();
    cellObjetivos.addElement(objetivosHead);
    cellObjetivos.addElement(Chunk.NEWLINE);
    List objetivosList = new List(List.ORDERED, List.ALPHABETICAL);
    objetivosList.setLowercase(true);
    for (ObjetivoDisciplinaDTO objetivoDisciplina : objetivosDisciplina) {
        ListItem item = new ListItem(objetivoDisciplina.getDescricao() + " (" + objetivoDisciplina.getNivelAprendizagem().getCodigo() + ")", fontManager.getDefaultFont());
        objetivosList.add(item);
    }
    cellObjetivos.addElement(objetivosList);
    cellObjetivos.setColspan(6);
    cellObjetivos.setPadding(10);
    cellObjetivos.setPaddingBottom(20);
    // cellObjetivos.setMinimumHeight(520);
    table.addCell(cellObjetivos);
    PdfPCell cellEmentas;
    cellEmentas = new PdfPCell();
    Paragraph ementaHead = new Paragraph("EMENTA: ", fontManager.getBoldFont());
    cellEmentas.addElement(ementaHead);
    cellEmentas.addElement(Chunk.NEWLINE);
    UnidadeDidaticaDTO[] unidades = teachingDocumentsService.findAllUnidadesDidaticas(disciplina.getId());
    List unidadesList = new List(List.ORDERED);
    for (UnidadeDidaticaDTO unidade : unidades) {
        ListItem itemUnidade = new ListItem(unidade.getDescricao(), fontManager.getDefaultFont());
        unidadesList.add(itemUnidade);
        SubunidadeDidaticaDTO[] subunidades = teachingDocumentsService.findAllSubunidadesDidaticas(unidade.getId());
        List subuniaddesList = new List(List.UNORDERED);
        subuniaddesList.setIndentationLeft(15);
        for (SubunidadeDidaticaDTO subunidade : subunidades) {
            ListItem itemSubunidade = new ListItem(subunidade.getDescricao(), fontManager.getDefaultFont());
            subuniaddesList.add(itemSubunidade);
        }
        unidadesList.add(subuniaddesList);
    }
    cellEmentas.addElement(unidadesList);
    cellEmentas.setColspan(6);
    cellEmentas.setPadding(10);
    cellEmentas.setPaddingBottom(20);
    table.addCell(cellEmentas);
    return table;
}
Also used : SubunidadeDidaticaDTO(com.tomasio.projects.trainning.dto.SubunidadeDidaticaDTO) Phrase(com.itextpdf.text.Phrase) Chunk(com.itextpdf.text.Chunk) UnidadeDidaticaDTO(com.tomasio.projects.trainning.dto.UnidadeDidaticaDTO) Paragraph(com.itextpdf.text.Paragraph) ArrayList(java.util.ArrayList) List(com.itextpdf.text.List) ListItem(com.itextpdf.text.ListItem) ObjetivoDisciplinaDTO(com.tomasio.projects.trainning.dto.ObjetivoDisciplinaDTO)

Example 3 with Chunk

use of com.itextpdf.text.Chunk in project TranskribusCore by Transkribus.

the class TrpPdfDocument method addUniformTextFromTextRegion.

private void addUniformTextFromTextRegion(final TextRegionType tr, final PdfContentByte cb, int cutoffLeft, int cutoffTop, BaseFont bf, float lineStartX, ExportCache cache) throws IOException, DocumentException {
    List<TextLineType> lines = tr.getTextLine();
    if (lines != null && !lines.isEmpty()) {
        int i = 0;
        float lineStartY = 0;
        // sort according to reading order
        Collections.sort(lines, new TrpElementReadingOrderComparator<TextLineType>(true));
        double minY = 0;
        double maxY = 0;
        // get min and max values of region y direction for later calculation of textline height
        // java.awt.Rectangle regionRect = PageXmlUtils.buildPolygon(tr.getCoords().getPoints()).getBounds();
        int maxIdx = lines.size() - 1;
        // java.awt.Rectangle firstLineRectOld = PageXmlUtils.buildPolygon(lines.get(0).getCoords().getPoints()).getBounds();
        // logger.debug("OLDDDDD: firstLineRectOld minX = " + firstLineRectOld.getMinX());
        java.awt.Rectangle firstLineRect = ((TrpTextLineType) lines.get(0)).getBoundingBox();
        // logger.debug("NEWWWWW: firstLineRect minX = " + firstLineRect.getMinX());
        // java.awt.Rectangle lastLineRect = PageXmlUtils.buildPolygon(lines.get(maxIdx).getCoords().getPoints()).getBounds();
        java.awt.Rectangle lastLineRect = ((TrpTextLineType) lines.get(maxIdx)).getBoundingBox();
        double firstLineRotation = computeRotation((TrpBaselineType) lines.get(0).getBaseline());
        double lastLineRotation = computeRotation((TrpBaselineType) lines.get(maxIdx).getBaseline());
        boolean isVerticalRegion = false;
        // use X coords to compute the total line gap
        if (firstLineRotation == 90 && lastLineRotation == 90) {
            // since the reading order is not clear if the text is vertically -> could be right to left or vice versa
            double tmpMinX1 = firstLineRect.getMinX();
            double tmpMinX2 = lastLineRect.getMinX();
            double tmpMaxX1 = firstLineRect.getMaxX();
            double tmpMaxX2 = lastLineRect.getMaxX();
            minY = Math.min(tmpMinX1, tmpMinX2);
            maxY = Math.max(tmpMaxX1, tmpMaxX2);
            isVerticalRegion = true;
        } else {
            minY = firstLineRect.getMinY();
            maxY = lastLineRect.getMaxY();
        }
        /*
			 * if start of line is too tight on the upper bound - set to the first 1/12 of t page from above
			 * BUT: Is not good since page number and other informations are often in this section
			 */
        // if (minY < twelfthPoints[1][1]){
        // minY = twelfthPoints[1][1];
        // }
        // for(TextLineType lt : lines){
        // 
        // TrpTextLineType l = (TrpTextLineType)lt;
        // java.awt.Rectangle lineRect = PageXmlUtils.buildPolygon(l.getCoords().getPoints()).getBounds();
        // 
        // 
        // 
        // if (lines.size() == 1){
        // minY = lineRect.getMinY();
        // maxY = lineRect.getMaxY();
        // 
        // }
        // else if (l.getIndex() == 0){
        // minY = lineRect.getMinY();
        // }
        // else if (l.getIndex() == lines.size()-1){
        // maxY = lineRect.getMaxY();
        // }
        // 
        // }
        double lineGap = (maxY - minY) / lines.size();
        // use default values if only one line  and no previous line mean height computed
        if (lines.size() == 1) {
            lineMeanHeight = (prevLineMeanHeight != 0 ? prevLineMeanHeight : lineMeanHeight);
        } else if (lines.size() > 1) {
            lineMeanHeight = (float) (2 * (lineGap / 3));
            leading = (int) (lineGap / 3);
            prevLineMeanHeight = lineMeanHeight;
        // logger.debug("Line Mean Height for Export " + lineMeanHeight);
        // overallLineMeanHeight = ( (overallLineMeanHeight != 0) ? overallLineMeanHeight+lineMeanHeight/2 : lineMeanHeight);
        }
        for (TextLineType lt : lines) {
            wordOffset = 0;
            TrpTextLineType l = (TrpTextLineType) lt;
            TrpBaselineType baseline = (TrpBaselineType) l.getBaseline();
            // PageXmlUtils.buildPolygon(l.getCoords().getPoints()).getBounds();
            java.awt.Rectangle lineRect = l.getBoundingBox();
            // PageXmlUtils.buildPolygon(baseline.getPoints()).getBounds();
            java.awt.Rectangle baseLineRect = baseline == null ? null : baseline.getBoundingBox();
            if (baseLineRect == null) {
                logger.debug("Baseline is null - ignore this line");
                continue;
            }
            float tmpLineStartX = lineStartX;
            // PageXmlUtils.buildPolygon(tr.getCoords().getPoints()).getBounds().getMinX();
            float regionStartMinX = (float) tr.getBoundingBox().getMinX();
            double regionWidth = tr.getBoundingBox().getWidth();
            // first line
            if (i == 0) {
                lineStartY = (float) (minY + lineMeanHeight);
                /*
					 * if first line of a text region is indented then take this into account in printed text
					 */
                if (lineRect.getMinX() > regionStartMinX) {
                    if (lineRect.getMinX() - regionStartMinX > regionWidth / 4) {
                        // tmpLineStartX = (float) lineStartX + twelfthPoints[1][0];
                        tmpLineStartX = (float) baseLineRect.getMinX();
                    }
                }
            } else // for subsequent lines
            {
                if (lineRect.getMinX() > regionStartMinX) {
                    if (lineRect.getMinX() - regionStartMinX > regionWidth / 4) {
                        // tmpLineStartX = (float) lineStartX + twelfthPoints[1][0];
                        tmpLineStartX = (float) baseLineRect.getMinX();
                    }
                }
                // tmpLineStartX = getLinePositionInTextregionGrid(twelfthRegion, lineRect.getMinX());
                lineStartY = lineStartY + lineMeanHeight + leading;
            // for (TrpTextRegionType region : tr.getPage().getTextRegions(true)){
            // 
            // double regionMinX = PageXmlUtils.buildPolygon(region.getCoords().getPoints()).getBounds().getMinX();
            // double regionMaxX = PageXmlUtils.buildPolygon(region.getCoords().getPoints()).getBounds().getMaxX();
            // Rectangle rec = PageXmlUtils.buildPolygon(region.getCoords().getPoints()).getBounds();
            // 
            // if (rec.contains(tmpLineStartX, lineStartY) && !tr.getId().equals(region.getId()) && tmpLineStartX < regionMaxX){
            // logger.debug("region contains point " + tr.getId() + " region ID " + region.getId());
            // tmpLineStartX = (float) regionMaxX;
            // break;
            // }
            // 
            // 
            // }
            // if (lineRect.getMinX() > lineStartX){
            // if (lineRect.getMinX() - lineStartX > twelfthPoints[1][0]){
            // tmpLineStartX = (float) lineRect.getMinX();
            // }
            // }
            }
            if (baseLineRect != null && regionStartMinX < baseLineRect.getMinX() && (baseLineRect.getMinX() - regionStartMinX) > twelfthPoints[1][0]) {
                // logger.debug("try to find smaller region for baseline !!!!!!! " );
                for (TrpTextRegionType region : tr.getPage().getTextRegions(false)) {
                    if (!region.getId().equals(tr.getId())) {
                        // PageXmlUtils.buildPolygon(region.getCoords().getPoints()).getBounds().getMinX();
                        double regionMinX = region.getBoundingBox().getMinX();
                        double regionMaxX = region.getBoundingBox().getMaxX();
                        double regionMinY = region.getBoundingBox().getMinY();
                        double regionMaxY = region.getBoundingBox().getMaxY();
                        double meanX = regionMinX + (regionMaxX - regionMinX) / 2;
                        // another region before the lines
                        if (meanX > regionStartMinX && meanX < baseLineRect.getMinX() && baseLineRect.getMinY() < regionMaxY && baseLineRect.getMinY() > regionMinY) {
                            tmpLineStartX = (float) regionMaxX + lineMeanHeight;
                            logger.debug("region " + region.getId() + " overlaps this other region " + tr.getId());
                            // logger.debug("new tmplineStartX is " + regionMaxX);
                            break;
                        }
                    }
                }
            // tmpLineStartX = (float) baseLineRect.getMinX();
            }
            i++;
            /*
				 * word level bei uniform output nicht sinnvoll?
				 * besser nur ganze lines ausgeben
				 */
            // if(useWordLevel && !l.getWord().isEmpty()){
            // List<WordType> words = l.getWord();
            // for(WordType wt : words){
            // TrpWordType w = (TrpWordType)wt;
            // if(!w.getUnicodeText().isEmpty()){
            // java.awt.Rectangle boundRect = PageXmlUtils.buildPolygon(w.getCoords()).getBounds();
            // 
            // addUniformString(boundRect, lineMeanHeight, lineStartX, lineStartY, w.getUnicodeText(), cb, cutoffLeft, cutoffTop, bf);
            // } else {
            // logger.info("No text content in word: " + w.getId());
            // }
            // }
            // } else if(!l.getUnicodeText().isEmpty()){
            /*
				 * make chunks out of the lineText
				 * so it is possible to have differnt fonts, underlines and other text styles in one line
				 * 
				 * possible text styles are:
				 * 		new CustomTagAttribute("fontFamily", true, "Font family", "Font family"),
						new CustomTagAttribute("serif", true, "Serif", "Is this a serif font?"),
						new CustomTagAttribute("monospace",true, "Monospace", "Is this a monospace (i.e. equals width characters) font?"),
						new CustomTagAttribute("fontSize", true, "Font size", "The size of the font in points"),
						new CustomTagAttribute("kerning", true, "Kerning", "The kerning of the font, see: http://en.wikipedia.org/wiki/Kerning"),
						new CustomTagAttribute("textColour", true, "Text colour", "The foreground colour of the text"),
						new CustomTagAttribute("bgColour", true, "Background colour", "The background colour of the text"),
						new CustomTagAttribute("reverseVideo", true, "Reverse video", "http://en.wikipedia.org/wiki/Reverse_video"),
						new CustomTagAttribute("bold", true, "Bold", "Bold font"),
						new CustomTagAttribute("italic", true, "Italic", "Italic font"),
						new CustomTagAttribute("underlined", true, "Underlined", "Underlined"),
						new CustomTagAttribute("subscript", true, "Subscript", "Subscript"),
						new CustomTagAttribute("superscript", true, "Superscript", "Superscript"),
						new CustomTagAttribute("strikethrough", true, "Strikethrough", "Strikethrough"),
						new CustomTagAttribute("smallCaps", true, "Small caps", "Small capital letters at the height as lowercase letters, see: http://en.wikipedia.org/wiki/Small_caps"),
						new CustomTagAttribute("letterSpaced", true, "Letter spaced", "Equals distance between characters, see: http://en.wikipedia.org/wiki/Letter-spacing"),
				 */
            List<Chunk> chunkList = new ArrayList<Chunk>();
            /*
				 * if line is empty -> use the words of this line as line text
				 * otherwise take the text in the line
				 */
            List<TextStyleTag> styleTags = new ArrayList<TextStyleTag>();
            String shapeText = "";
            if (l.getUnicodeText().isEmpty() || useWordLevel) {
                // logger.debug("in word based path " + useWordLevel);
                List<WordType> words = l.getWord();
                int chunkIndex = 0;
                for (WordType wt : words) {
                    TrpWordType w = (TrpWordType) wt;
                    String wordText = "";
                    // add empty space after each word
                    if (chunkIndex > 0) {
                        chunkList.add(chunkIndex, new Chunk(" "));
                        chunkIndex++;
                    }
                    if (!w.getUnicodeText().isEmpty()) {
                        // remember all style tags for text formatting later on
                        styleTags.addAll(w.getTextStyleTags());
                        if (!shapeText.equals("")) {
                            shapeText = shapeText.concat(" ");
                        }
                        wordText = wordText.concat(w.getUnicodeText());
                        shapeText = shapeText.concat(w.getUnicodeText());
                        for (int j = 0; j < wordText.length(); ++j) {
                            String currentCharacter = wordText.substring(j, j + 1);
                            chunkList.add(chunkIndex, formatText(currentCharacter, styleTags, j, w, cache));
                            chunkIndex++;
                        }
                        styleTags.clear();
                    }
                }
            } else if (!l.getUnicodeText().isEmpty()) {
                String lineText = l.getUnicodeText();
                shapeText = lineText;
                // logger.debug("line Text is " + lineText);
                styleTags.addAll(l.getTextStyleTags());
                for (int j = 0; j < lineText.length(); ++j) {
                    String currentCharacter = lineText.substring(j, j + 1);
                    chunkList.add(j, formatText(currentCharacter, styleTags, j, l, cache));
                }
            } else // empty shape
            {
                logger.debug("empty shape ");
                continue;
            }
            Phrase phrase = new Phrase();
            // trim is important to get the 'real' first char for rtl definition
            boolean rtl = textIsRTL(shapeText.trim());
            if (rtl) {
                logger.debug("&&&&&&&& STRING IS RTL : ");
            }
            for (int j = chunkList.size() - 1; j >= 0; j--) {
                if (rtl) {
                    phrase.add(chunkList.get(j));
                } else {
                    phrase.addAll(chunkList);
                    break;
                }
            }
            // phrase.addAll(chunkList);
            // logger.debug("curr phrase is: " + phrase.getContent());
            // compute rotation of text, if rotation higher PI/16 than rotate otherwise even text
            /*
				 * No rotation for single lines in a overall horizontal text region 
				 * Reason: Vertical line uses too much space - calculated for horizontal
				 */
            double rotation = 0;
            if (isVerticalRegion) {
                rotation = (baseline != null ? computeRotation(baseline) : 0);
                if (rotation != 0) {
                    /*
						 * if we rotate e.g. 90° than we should use the actual x location of the line
						 * so vertical text must be treated different than horizontal text 
						 */
                    if (baseLineRect != null) {
                        if (rtl) {
                            tmpLineStartX = (float) baseLineRect.getMaxX();
                        } else {
                            tmpLineStartX = (float) baseLineRect.getMinX();
                        }
                        lineStartY = (float) baseLineRect.getMaxY();
                    } else if (lineRect != null) {
                        tmpLineStartX = lineRect.x;
                        lineStartY = (float) lineRect.getMaxY();
                    }
                }
            }
            // blacken Strings if wanted
            // Set<Entry<CustomTag, String>> blackSet = CustomTagUtils.getAllTagsOfThisTypeForShapeElement(l, RegionTypeUtil.BLACKENING_REGION.toLowerCase()).entrySet();
            // 
            // if (!lineText.equals("") && doBlackening && blackSet.size() > 0){
            // 
            // //for all blackening regions replace text with ****
            // for (Map.Entry<CustomTag, String> currEntry : blackSet){
            // 
            // if (!currEntry.getKey().isIndexed()){
            // //logger.debug("line not indexed : " + lineText);
            // lineText = lineText.replaceAll(".", "*");
            // }
            // else{
            // lineText = blackenString(currEntry, lineText);
            // //logger.debug("lineText after blackened : " + lineText);
            // }
            // }
            // }
            // for rtl export
            float lineEndX = 0;
            float width = 0;
            if (baseLineRect != null) {
                lineEndX = (float) baseLineRect.getMaxX();
                width = (float) baseLineRect.getWidth();
            // this leads to an extra start for each line instead of having a combined start for all lines in a region
            // tmpLineStartX = (float) (lineEndX - baseLineRect.getWidth());
            } else if (lineRect != null) {
                lineEndX = lineRect.x + lineRect.width;
                width = (float) lineRect.getWidth();
            }
            // mainly for very small regions at the very left of a page
            if (tmpLineStartX > lineEndX) {
                lineEndX = tmpLineStartX + width;
            }
            // logger.debug("width " + width);
            // logger.debug("lineEndX " + lineEndX);
            // first add uniform String (=line), ,after that eventaully highlight the tags in this line using the current line information like x/y position,
            // addUniformString(lineMeanHeight, tmpLineStartX, lineStartY, lineText, cb, cutoffLeft, cutoffTop, bf, twelfthPoints[1][0], false, null, rotation);
            addUniformString(tr.getBoundingBox(), lineMeanHeight, tmpLineStartX, lineStartY, lineEndX, phrase, cb, cutoffLeft, cutoffTop, bf, twelfthPoints[1][0], false, null, rotation, rtl);
        /*
				 * old:
				 * highlight all tags of this text line if property is set
				 * no highlighting is done during chunk formatting and not in an extra step
				 */
        // if (highlightTags){
        // 
        // 
        // Set<Entry<CustomTag, String>> entrySet = CustomTagUtils.getAllTagsForShapeElement(l).entrySet();
        // 
        // highlightUniformString(entrySet, tmpLineStartX, lineStartY, l, cb, cutoffLeft, cutoffTop, bf);
        // 
        // List<WordType> words = l.getWord();
        // for(WordType wt : words){
        // TrpWordType w = (TrpWordType)wt;
        // 
        // Set<Entry<CustomTag, String>> entrySet2 = CustomTagUtils.getAllTagsForShapeElement(w).entrySet();
        // 
        // highlightUniformString(entrySet2, tmpLineStartX, lineStartY, l, cb, cutoffLeft, cutoffTop, bf);
        // }
        // 
        // }
        }
    }
}
Also used : Rectangle(java.awt.Rectangle) ArrayList(java.util.ArrayList) Phrase(com.itextpdf.text.Phrase) Chunk(com.itextpdf.text.Chunk) TrpWordType(eu.transkribus.core.model.beans.pagecontent_trp.TrpWordType) Point(java.awt.Point) WordType(eu.transkribus.core.model.beans.pagecontent.WordType) TrpWordType(eu.transkribus.core.model.beans.pagecontent_trp.TrpWordType) TrpTextLineType(eu.transkribus.core.model.beans.pagecontent_trp.TrpTextLineType) TrpBaselineType(eu.transkribus.core.model.beans.pagecontent_trp.TrpBaselineType) TextStyleTag(eu.transkribus.core.model.beans.customtags.TextStyleTag) TextLineType(eu.transkribus.core.model.beans.pagecontent.TextLineType) TrpTextLineType(eu.transkribus.core.model.beans.pagecontent_trp.TrpTextLineType) TrpTextRegionType(eu.transkribus.core.model.beans.pagecontent_trp.TrpTextRegionType)

Example 4 with Chunk

use of com.itextpdf.text.Chunk in project TranskribusCore by Transkribus.

the class TrpPdfDocument method formatText.

private Chunk formatText(String currCharacter, List<TextStyleTag> styleTags, int currentIndex, ITrpShapeType currShape, ExportCache cache) throws IOException {
    // first blacken char if needed
    Set<Entry<CustomTag, String>> blackSet = ExportUtils.getAllTagsOfThisTypeForShapeElement(currShape, RegionTypeUtil.BLACKENING_REGION.toLowerCase()).entrySet();
    if (!currCharacter.equals("") && doBlackening && blackSet.size() > 0) {
        // for all blackening regions replace text with ****
        for (Map.Entry<CustomTag, String> currEntry : blackSet) {
            int beginIndex = currEntry.getKey().getOffset();
            int endIndex = beginIndex + currEntry.getKey().getLength();
            if (currentIndex >= beginIndex && currentIndex < endIndex) {
                currCharacter = "*";
            }
        }
    }
    // create new chunk
    Chunk currChunk = new Chunk(currCharacter);
    // Font arial = new Font(bfArial, lineMeanHeight);
    // Font arialBold = new Font(bfArialBold, lineMeanHeight);
    // Font arialItalic = new Font(bfArialItalic, lineMeanHeight);
    currChunk.setFont(fontArial);
    Set<Entry<CustomTag, String>> commentSet = ExportUtils.getAllTagsOfThisTypeForShapeElement(currShape, "comment").entrySet();
    for (Map.Entry<CustomTag, String> currEntry : commentSet) {
        int beginIndex = currEntry.getKey().getOffset();
        int endIndex = beginIndex + currEntry.getKey().getLength();
        if (currentIndex >= beginIndex && currentIndex < endIndex) {
            // hex string #FFF8B0: yellow color
            currChunk.setBackground(new BaseColor(Color.decode("#FFF8B0").getRGB()));
        }
    }
    /*
		 * format according to custom style tag - check for each char in the text if a special style should be set
		 */
    for (TextStyleTag styleTag : styleTags) {
        if (currentIndex >= (wordOffset + styleTag.getOffset()) && currentIndex < (wordOffset + styleTag.getOffset() + styleTag.getLength())) {
            if (CoreUtils.val(styleTag.getBold())) {
                // logger.debug("BOOOOOOOOOLD");
                currChunk.setFont(fontArialBold);
            }
            if (CoreUtils.val(styleTag.getItalic())) {
                // logger.debug("ITAAAAAAAAAAAALIC");
                currChunk.setFont(fontArialItalic);
            }
            if (CoreUtils.val(styleTag.getStrikethrough())) {
                // logger.debug("Striiiiiiiiikethrough");
                currChunk.setUnderline(0.2f, 3f);
            }
            // }
            if (CoreUtils.val(styleTag.getUnderlined())) {
                // logger.debug("Underliiiiiiined");
                currChunk.setUnderline(0.2f, -3f);
            }
        }
    }
    if (highlightTags) {
        Set<Entry<CustomTag, String>> entrySet;
        entrySet = ExportUtils.getAllTagsForShapeElement(currShape).entrySet();
        int k = 1;
        int tagId = 0;
        int[] prevLength = new int[entrySet.size()];
        int[] prevOffset = new int[entrySet.size()];
        for (Map.Entry<CustomTag, String> currEntry : entrySet) {
            // Set<String> wantedTags = ExportUtils.getOnlyWantedTagnames(CustomTagFactory.getRegisteredTagNames());
            Set<String> wantedTags = cache.getOnlySelectedTagnames(CustomTagFactory.getRegisteredTagNames());
            if (wantedTags.contains(currEntry.getKey().getTagName())) {
                // logger.debug("current tag name "+ currEntry.getKey().getTagName());
                // logger.debug("current tag text "+ currEntry.getKey().getContainedText());
                String color = CustomTagFactory.getTagColor(currEntry.getKey().getTagName());
                int currLength = currEntry.getKey().getLength();
                int currOffset = wordOffset + currEntry.getKey().getOffset();
                if (color != null && currentIndex >= (currOffset) && currentIndex <= (currOffset + currLength)) {
                    /**
                     * if the current tag overlaps one of the previous tags
                     * -> increase the distance of the line under the textline
                     */
                    if (isOverlaped(prevOffset, prevLength, currOffset, currLength)) {
                        k++;
                    // logger.debug("overlapped is true, k = " + k);
                    } else {
                        k = 1;
                    // logger.debug("overlapped is not true, k = " + k);
                    }
                    currChunk.setUnderline(new BaseColor(Color.decode(color).getRGB()), 0.8f, 0.0f, -2f * +1f * k, 0.0f, PdfContentByte.LINE_CAP_BUTT);
                // logger.debug("UNDERLINE curr chunk " + currChunk.getContent() + " k = " + k);
                }
                prevOffset[tagId] = currOffset;
                prevLength[tagId] = currLength;
                tagId++;
            // yShift -> vertical shift of underline if several tags are at the same position
            // float yShift = (lineMeanHeight/6) * k;
            }
        }
    }
    // logger.debug("chunk content is " + currChunk.getContent());
    return currChunk;
}
Also used : Entry(java.util.Map.Entry) BaseColor(com.itextpdf.text.BaseColor) TextStyleTag(eu.transkribus.core.model.beans.customtags.TextStyleTag) CustomTag(eu.transkribus.core.model.beans.customtags.CustomTag) Chunk(com.itextpdf.text.Chunk) Map(java.util.Map) HashMap(java.util.HashMap) Point(java.awt.Point)

Example 5 with Chunk

use of com.itextpdf.text.Chunk in project summer-bean by cn-cerc.

the class ExportPdf method export.

public void export(String message) throws DocumentException, IOException {
    // 清空输出流
    response.reset();
    // 第一步
    Document document = new Document(PageSize.A4.rotate());
    // 第二步
    // PdfWriter.getInstance(pdf, new FileOutputStream("Hello.pdf"));
    ByteArrayOutputStream pdfStream = new ByteArrayOutputStream();
    // 第三步
    document.open();
    // 第四步
    document.addAuthor("地藤系统");
    document.addSubject("地藤系统报表文件");
    document.addCreationDate();
    document.add(new Chunk(message));
    // 第五步
    document.close();
    // 第六步
    response.setContentType("application/pdf");
    response.setContentLength(pdfStream.size());
    ServletOutputStream out = response.getOutputStream();
    pdfStream.writeTo(out);
    out.flush();
    response.flushBuffer();
}
Also used : ServletOutputStream(javax.servlet.ServletOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Document(com.itextpdf.text.Document) Chunk(com.itextpdf.text.Chunk)

Aggregations

Chunk (com.itextpdf.text.Chunk)11 Paragraph (com.itextpdf.text.Paragraph)6 Phrase (com.itextpdf.text.Phrase)6 ArrayList (java.util.ArrayList)5 BaseColor (com.itextpdf.text.BaseColor)3 Font (com.itextpdf.text.Font)3 List (com.itextpdf.text.List)3 ListItem (com.itextpdf.text.ListItem)3 PdfPCell (com.itextpdf.text.pdf.PdfPCell)3 PdfPTable (com.itextpdf.text.pdf.PdfPTable)3 Document (com.itextpdf.text.Document)2 ObjetivoDisciplinaDTO (com.tomasio.projects.trainning.dto.ObjetivoDisciplinaDTO)2 SubunidadeDidaticaDTO (com.tomasio.projects.trainning.dto.SubunidadeDidaticaDTO)2 TextStyleTag (eu.transkribus.core.model.beans.customtags.TextStyleTag)2 Point (java.awt.Point)2 ScriptCoverageStatistics (com.github.timurstrekalov.saga.core.model.ScriptCoverageStatistics)1 Chapter (com.itextpdf.text.Chapter)1 BaseFont (com.itextpdf.text.pdf.BaseFont)1 ObjetivoOperacionalizadoDTO (com.tomasio.projects.trainning.dto.ObjetivoOperacionalizadoDTO)1 ObjetivoUnidadeDidaticaDTO (com.tomasio.projects.trainning.dto.ObjetivoUnidadeDidaticaDTO)1