Skip to content

Commit

Permalink
fix: resolve SpotBugs issues
Browse files Browse the repository at this point in the history
Fixed all issues identified by SpotBugs static analysis tool to improve code quality
  • Loading branch information
Joabsonlg committed Nov 23, 2024
1 parent fb53c34 commit 46d3dd0
Show file tree
Hide file tree
Showing 14 changed files with 582 additions and 617 deletions.
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
package io.github.joabsonlg.pdfbuilder.components.image;

import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.util.Matrix;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.font.Standard14Fonts;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.util.Matrix;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.awt.Dimension;

/**
* Componente para renderização de imagens em documentos PDF.
Expand Down Expand Up @@ -45,34 +45,36 @@ private Image(Builder builder) {
* Renderiza a imagem no PDPageContentStream.
*/
public float render(PDPageContentStream contentStream, float x, float y, float availableWidth, float imageWidth) throws IOException {
// Calcula as dimensões com base na qualidade
float adjustedWidth = width * quality;
float adjustedHeight = height * quality;

// Calcula a posição X baseada no alinhamento
float xPos = switch (alignment) {
case CENTER -> x + (availableWidth - imageWidth) / 2;
case RIGHT -> x + (availableWidth - imageWidth);
case CENTER -> x + (availableWidth - adjustedWidth) / 2;
case RIGHT -> x + (availableWidth - adjustedWidth);
default -> x;
};

float imageHeight = (imageWidth / width) * height;

// Salva o estado gráfico atual
contentStream.saveGraphicsState();

// Aplica rotação se necessário
if (rotation != 0) {
float centerX = xPos + imageWidth / 2;
float centerY = y - imageHeight / 2;
float centerX = xPos + adjustedWidth / 2;
float centerY = y - adjustedHeight / 2;
contentStream.transform(
Matrix.getRotateInstance(Math.toRadians(rotation), centerX, centerY)
Matrix.getRotateInstance(Math.toRadians(rotation), centerX, centerY)
);
}

// Renderiza a imagem
contentStream.drawImage(image, xPos, y - imageHeight, imageWidth, imageHeight);
// Renderiza a imagem com dimensões ajustadas
contentStream.drawImage(image, xPos, y - adjustedHeight, adjustedWidth, adjustedHeight);

// Restaura o estado gráfico
contentStream.restoreGraphicsState();

float newY = y - imageHeight;
float newY = y - adjustedHeight;

// Adiciona legenda se existir
if (caption != null && !caption.isEmpty()) {
Expand All @@ -81,20 +83,12 @@ public float render(PDPageContentStream contentStream, float x, float y, float a
contentStream.setFont(font, captionFontSize);

float captionWidth = font.getStringWidth(caption) / 1000 * captionFontSize;
float captionX;

// Alinha a legenda com a imagem
switch (alignment) {
case CENTER:
captionX = xPos + (imageWidth - captionWidth) / 2;
break;
case RIGHT:
captionX = xPos + imageWidth - captionWidth;
break;
default: // LEFT
captionX = xPos;
break;
}
float captionX = switch (alignment) {
case CENTER -> xPos + (imageWidth - captionWidth) / 2;
case RIGHT -> xPos + imageWidth - captionWidth;
default -> // LEFT
xPos;
};

contentStream.newLineAtOffset(captionX, newY - captionFontSize - 5);
contentStream.showText(caption);
Expand All @@ -110,7 +104,7 @@ public float render(PDPageContentStream contentStream, float x, float y, float a
* Retorna as dimensões atuais da imagem.
*/
public Dimension getDimensions() {
return new Dimension((int)width, (int)height);
return new Dimension((int) width, (int) height);
}

public static Builder builder(PDDocument document, File imageFile) throws IOException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,6 @@ public void render(PDPageContentStream contentStream, float pageWidth, float y,
// Calcula a largura do texto
float textWidth = style.getFont().getStringWidth(title) / 1000 * style.getFontSize();

// Calcula o espaço disponível para o texto considerando as imagens
float availableWidth = contentWidth;
float imageSpace = 0;
if (leftImage != null || rightImage != null) {
imageSpace = style.getImageWidth() + (2 * style.getImageMargin());
availableWidth -= (2 * imageSpace); // Espaço para ambas as imagens
}

// Renderiza a imagem da esquerda
if (leftImage != null) {
float imageX = marginLeft + style.getImageMargin();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ public float render(PDPageContentStream contentStream, float x, float y, float a
for (int i = 0; i < adjustedColumnWidths.length; i++) {
adjustedColumnWidths[i] *= scaleFactor;
}
tableWidth = availableWidth;
}

// Desenha o cabeçalho
Expand All @@ -77,7 +76,7 @@ public float render(PDPageContentStream contentStream, float x, float y, float a
}

private float drawRow(PDPageContentStream contentStream, List<String> row, float x, float y, boolean isHeader, float[] columnWidths) throws IOException {
float currentX = x;
float currentX;
Color bgColor = isHeader ? headerBackgroundColor : null;
Color txtColor = isHeader ? headerTextColor : textColor;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,9 @@ public float render(PDPageContentStream contentStream, float x, float y, float m
startX = x + maxWidth - textWidth;
}

// Aplica o espaçamento antes
y -= spacingBefore;

// Renderiza o texto
contentStream.beginText();
contentStream.newLineAtOffset(startX, y);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,19 +59,13 @@ public PDFBuilder(PDFConfiguration config) {

try {
this.contentStream = new PDPageContentStream(document, currentPage);
// Inicializa a posição atual no topo da página
this.currentPosition = Coordinates.origin(config.getPageSize(), config.getSafeArea())
.moveTo(
config.getSafeArea().getMarginLeft(),
config.getPageSize().getHeight() - config.getSafeArea().getMarginTop()
);

// Adiciona o logo na primeira página se existir
if (logo != null) {
addLogo();
}
} catch (IOException e) {
throw new RuntimeException("Erro ao criar PDFBuilder", e);
LOGGER.error("Erro ao gerar o PDF: {}", e.getMessage(), e);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,16 @@
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.font.Standard14Fonts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

public final class CompleteExample {
private static final Logger LOGGER = LoggerFactory.getLogger(CompleteExample.class);

private CompleteExample() {
throw new UnsupportedOperationException("This is a utility class and cannot be instantiated");
Expand Down Expand Up @@ -66,12 +70,6 @@ public static void main(String[] args) {
.withColor(Color.BLACK)
.build();

TextStyle blueStyle = TextStyle.builder()
.withFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA_BOLD))
.withFontSize(HeadingLevel.H1.getFontSize())
.withColor(new Color(0, 102, 204))
.build();

// Configura o logo
LogoStyle logoStyle = LogoStyle.builder()
.withFontSize(16f)
Expand All @@ -85,7 +83,7 @@ public static void main(String[] args) {
.build();

// Configura o logo com imagens
String imagePath = "C:\\Users\\joabs\\Documents\\Projetos\\MeusProjetos\\pdf-builder-workspace\\pdf-builder\\src\\main\\java\\br\\com\\nutit\\pdfbuilder\\examples\\sample-image.jpg";
String imagePath = "src/main/java/io/github/joabsonlg/pdfbuilder/examples/sample-image.jpg";
builder.setLogo("PDF Builder - Exemplo Completo", logoStyle, imagePath, imagePath);

// Configura a numeração de páginas
Expand Down Expand Up @@ -204,8 +202,8 @@ public static void main(String[] args) {
// Salva o documento
builder.save("complete-example.pdf");

} catch (Exception e) {
e.printStackTrace();
} catch (IOException e) {
LOGGER.error("Erro ao gerar o PDF: {}", e.getMessage(), e);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,14 @@
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.font.Standard14Fonts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.awt.Color;
import java.awt.*;
import java.io.IOException;

public final class HeaderFooterDemo {
private static final Logger LOGGER = LoggerFactory.getLogger(HeaderFooterDemo.class);

private HeaderFooterDemo() {
throw new UnsupportedOperationException("This is a utility class and cannot be instantiated");
Expand Down Expand Up @@ -57,21 +61,19 @@ public static void main(String[] args) {

// Configura o logo (título do documento)
LogoStyle logoStyle = LogoStyle.builder()
.withFontSize(16f)
.withColor(Color.BLACK)
.withMarginBottom(20f)
.withDrawLine(true)
.withLineWidth(1f)
.withLineColor(new Color(43, 43, 43, 128))
.withImageHeight(30f) // Altura das imagens do logo
.withImageMargin(10f) // Margem das imagens
.build();
.withFontSize(16f)
.withColor(Color.BLACK)
.withMarginBottom(20f)
.withDrawLine(true)
.withLineWidth(1f)
.withLineColor(new Color(43, 43, 43, 128))
.withImageHeight(30f) // Altura das imagens do logo
.withImageMargin(10f) // Margem das imagens
.build();

// Caminhos das imagens do logo (exemplo)
String leftImagePath = "C:\\Users\\joabs\\Documents\\Projetos\\MeusProjetos\\pdf-builder-workspace\\pdf-builder\\src\\main\\java\\br\\com\\n" + //
"utit\\pdfbuilder\\examples\\sample-image.jpg"; // Substitua pelo caminho real da imagem
String rightImagePath = "C:\\Users\\joabs\\Documents\\Projetos\\MeusProjetos\\pdf-builder-workspace\\pdf-builder\\src\\main\\java\\br\\com\\n" + //
"utit\\pdfbuilder\\examples\\sample-image.jpg"; // Substitua pelo caminho real da imagem
String leftImagePath = "src/main/java/io/github/joabsonlg/pdfbuilder/examples/sample-image.jpg";
String rightImagePath = "src/main/java/io/github/joabsonlg/pdfbuilder/examples/sample-image.jpg";

// Adiciona o logo com imagens
builder.setLogo("PDF Builder", logoStyle, leftImagePath, rightImagePath);
Expand Down Expand Up @@ -120,9 +122,9 @@ public static void main(String[] args) {
// Salva o documento
builder.save("header-footer-demo.pdf");

System.out.println("PDF gerado com sucesso: header-footer-demo.pdf");
} catch (Exception e) {
e.printStackTrace();
LOGGER.info("PDF gerado com sucesso: header-footer-demo.pdf");
} catch (IOException e) {
LOGGER.error("Erro ao gerar o PDF: {}", e.getMessage(), e);
}
}
}
Loading

0 comments on commit 46d3dd0

Please sign in to comment.