Genera un'immagine BarCode personalizzata
Un codice a barre è una rappresentazione visiva di dati sotto forma di linee parallele o modelli. I codici a barre sono ampiamente utilizzati in vari settori come la vendita al dettaglio, la logistica, l’assistenza sanitaria, le banche e molti altri.
Microsoft Word consente agli utenti di incorporare i codici a barre direttamente nei documenti utilizzando i campi. Gli utenti possono inserire un tipo specifico di codice a barre, ad esempio un codice QR o un codice a barre lineare, utilizzando BARCODE campo.
In questo articolo, vedremo come il campo BARCODE è implementato in Aspose.Words e come Aspose.Words consente agli utenti di lavorare con documenti Word a cui è già stato aggiunto un codice a barre.
Tipi di codici a barre supportati da Aspose.Words
Aspose.Words supporta vari tipi di codici a barre. Il tipo di codice a barre viene passato come valore stringa nella proprietà BarcodeType.
Quando si salva in formati Word che supportano i codici a barre, è possibile utilizzare qualsiasi tipo di codice a barre supportato da Microsoft Word. Se è stato passato un tipo di codice a barre errato, Word visualizzerà un errore.
Quando si salva in altri formati, ad esempio PDF, Aspose.Words delega il rendering del codice a barre al codice utente, in modo che l’utente sia limitato ai tipi di codice a barre della loro implementazione o libreria utilizzata.
Inserire un codice a barre in un documento o caricare un documento con un codice a barre aggiunto
Aspose.Words fornisce la possibilità di:
- Inserire in modo programmatico un codice a barre in un documento DisplayBarcode e MergeBarcode codici di campo
- Oppure carica un documento Word con codici a barre già inseriti in esso per ulteriori lavori
Aspose.Words ha un’interfaccia per la generazione di codici a barre personalizzati che lo rende facile da usare Aspose.Words e Aspose.BarCode insieme per rendere le immagini dei codici a barre nei documenti di output. Ad esempio, è possibile creare un documento DOC, OOXML o RTF e aggiungere un campo DISPLAYBARCODE usando Aspose.Words. Oppure puoi caricare un documento DOC, OOXML o RTF con il campo DISPLAYBARCODE già esistente e fornire la tua implementazione di generatore di codici a barre personalizzato.
Un tipico campo DISPLAYBARCODE ha la seguente sintassi:
{ DISPLAYBARCODE "SomeData" QR \h 720 }
Di seguito è riportato un generatore di codice di esempio che utilizza Aspose.Words e Aspose.BarCode APIs. Questo esempio mostra come inserire le immagini del codice a barre nella posizione del campo DISPLAYBARCODE in un documento di Word:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git. | |
Document doc = new Document(getMyDir() + "Field sample - BARCODE.docx"); | |
doc.getFieldOptions().setBarcodeGenerator(new CustomBarcodeGenerator()); | |
doc.save(getArtifactsDir() + "WorkingWithBarcodeGenerator.GenerateACustomBarCodeImage.pdf"); |
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git. | |
public class CustomBarcodeGenerator extends DocsExamplesBase implements IBarcodeGenerator | |
{ | |
/// <summary> | |
/// Converts barcode image height from Word units to Aspose.BarCode units. | |
/// </summary> | |
/// <param name="heightInTwipsString"></param> | |
/// <returns></returns> | |
private static float convertSymbolHeight(String heightInTwipsString) throws Exception { | |
// Input value is in 1/1440 inches (twips). | |
int heightInTwips = tryParseInt(heightInTwipsString); | |
if (heightInTwips == Integer.MIN_VALUE) | |
throw new Exception("Error! Incorrect height - " + heightInTwipsString + "."); | |
// Convert to mm. | |
return (float) (heightInTwips * 25.4 / 1440.0); | |
} | |
/// <summary> | |
/// Converts barcode image color from Word to Aspose.BarCode. | |
/// </summary> | |
/// <param name="inputColor"></param> | |
/// <returns></returns> | |
private static Color convertColor(String inputColor) throws Exception { | |
// Input should be from "0x000000" to "0xFFFFFF". | |
int color = tryParseHex(inputColor.replace("0x", "")); | |
if (color == Integer.MIN_VALUE) | |
throw new Exception("Error! Incorrect color - " + inputColor + "."); | |
return new Color((color >> 16), ((color & 0xFF00) >> 8), (color & 0xFF)); | |
// Backward conversion - | |
// return string.Format("0x{0,6:X6}", mControl.ForeColor.ToArgb() & 0xFFFFFF); | |
} | |
/// <summary> | |
/// Converts bar code scaling factor from percent to float. | |
/// </summary> | |
/// <param name="scalingFactor"></param> | |
/// <returns></returns> | |
private static float convertScalingFactor(String scalingFactor) throws Exception { | |
boolean isParsed = false; | |
int percent = tryParseInt(scalingFactor); | |
if (percent != Integer.MIN_VALUE && percent >= 10 && percent <= 10000) | |
isParsed = true; | |
if (!isParsed) | |
throw new Exception("Error! Incorrect scaling factor - " + scalingFactor + "."); | |
return percent / 100.0f; | |
} | |
/// <summary> | |
/// Implementation of the GetBarCodeImage() method for IBarCodeGenerator interface. | |
/// </summary> | |
/// <param name="parameters"></param> | |
/// <returns></returns> | |
public BufferedImage getBarcodeImage(BarcodeParameters parameters) throws Exception { | |
if (parameters.getBarcodeType() == null || parameters.getBarcodeValue() == null) | |
return null; | |
BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.QR); | |
String type = parameters.getBarcodeType().toUpperCase(); | |
switch (type) | |
{ | |
case "QR": | |
generator = new BarcodeGenerator(EncodeTypes.QR); | |
break; | |
case "CODE128": | |
generator = new BarcodeGenerator(EncodeTypes.CODE_128); | |
break; | |
case "CODE39": | |
generator = new BarcodeGenerator(EncodeTypes.CODE_39_STANDARD); | |
break; | |
case "EAN8": | |
generator = new BarcodeGenerator(EncodeTypes.EAN_8); | |
break; | |
case "EAN13": | |
generator = new BarcodeGenerator(EncodeTypes.EAN_13); | |
break; | |
case "UPCA": | |
generator = new BarcodeGenerator(EncodeTypes.UPCA); | |
break; | |
case "UPCE": | |
generator = new BarcodeGenerator(EncodeTypes.UPCE); | |
break; | |
case "ITF14": | |
generator = new BarcodeGenerator(EncodeTypes.ITF_14); | |
break; | |
case "CASE": | |
generator = new BarcodeGenerator(EncodeTypes.NONE); | |
break; | |
} | |
if (generator.getBarcodeType().equals(EncodeTypes.NONE)) | |
return null; | |
generator.setCodeText(parameters.getBarcodeValue()); | |
if (generator.getBarcodeType().equals(EncodeTypes.QR)) | |
generator.getParameters().getBarcode().getCodeTextParameters().setTwoDDisplayText(parameters.getBarcodeValue()); | |
if (parameters.getForegroundColor() != null) | |
generator.getParameters().getBarcode().setBarColor(convertColor(parameters.getForegroundColor())); | |
if (parameters.getBackgroundColor() != null) | |
generator.getParameters().setBackColor(convertColor(parameters.getBackgroundColor())); | |
if (parameters.getSymbolHeight() != null) | |
{ | |
generator.getParameters().getImageHeight().setPixels(convertSymbolHeight(parameters.getSymbolHeight())); | |
generator.getParameters().setAutoSizeMode(AutoSizeMode.NONE); | |
} | |
generator.getParameters().getBarcode().getCodeTextParameters().setLocation(CodeLocation.NONE); | |
if (parameters.getDisplayText()) | |
generator.getParameters().getBarcode().getCodeTextParameters().setLocation(CodeLocation.BELOW); | |
generator.getParameters().getCaptionAbove().setText(""); | |
// Empiric scaling factor for converting Word barcode to Aspose.BarCode. | |
final float SCALE = 2.4f; | |
float xdim = 1.0f; | |
if (generator.getBarcodeType().equals(EncodeTypes.QR)) | |
{ | |
generator.getParameters().setAutoSizeMode(AutoSizeMode.NEAREST); | |
generator.getParameters().getImageWidth().setInches(generator.getParameters().getImageWidth().getInches() * SCALE); | |
generator.getParameters().getImageHeight().setInches(generator.getParameters().getImageWidth().getInches()); | |
xdim = generator.getParameters().getImageHeight().getInches() / 25; | |
generator.getParameters().getBarcode().getXDimension().setInches(xdim); | |
generator.getParameters().getBarcode().getBarHeight().setInches(xdim); | |
} | |
if (parameters.getScalingFactor() != null) | |
{ | |
float scalingFactor = convertScalingFactor(parameters.getScalingFactor()); | |
generator.getParameters().getImageHeight().setInches(generator.getParameters().getImageHeight().getInches() * scalingFactor); | |
if (generator.getBarcodeType().equals(EncodeTypes.QR)) | |
{ | |
generator.getParameters().getImageWidth().setInches(generator.getParameters().getImageHeight().getInches()); | |
generator.getParameters().getBarcode().getXDimension().setInches(xdim * scalingFactor); | |
generator.getParameters().getBarcode().getBarHeight().setInches(xdim * scalingFactor); | |
} | |
generator.getParameters().setAutoSizeMode(AutoSizeMode.NONE); | |
} | |
return generator.generateBarCodeImage(); | |
} | |
/// <summary> | |
/// Implementation of the GetOldBarcodeImage() method for IBarCodeGenerator interface. | |
/// </summary> | |
/// <param name="parameters"></param> | |
/// <returns></returns> | |
public BufferedImage getOldBarcodeImage(BarcodeParameters parameters) | |
{ | |
if (parameters.getPostalAddress() == null) | |
return null; | |
BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.POSTNET); | |
{ | |
generator.setCodeText(parameters.getPostalAddress()); | |
} | |
return generator.generateBarCodeImage(); | |
} | |
/// <summary> | |
/// Parses an integer using the invariant culture. Returns Int.MinValue if cannot parse. | |
/// | |
/// Allows leading sign. | |
/// Allows leading and trailing spaces. | |
/// </summary> | |
public static int tryParseInt(String s) { | |
try { | |
double value = Double.parseDouble(s); | |
return castDoubleToInt(value); | |
} catch (NumberFormatException e) { | |
return Integer.MIN_VALUE; | |
} | |
} | |
/// <summary> | |
/// Casts a double to int32 in a way that uint32 are "correctly" casted too (they become negative numbers). | |
/// </summary> | |
public static int castDoubleToInt(double value) | |
{ | |
long temp = (long) value; | |
return (int) temp; | |
} | |
/// <summary> | |
/// Try parses a hex String into an integer value. | |
/// on error return int.MinValue | |
/// </summary> | |
public static int tryParseHex(String s) | |
{ | |
try { | |
return Integer.parseInt(s); | |
} catch (NumberFormatException e) { | |
return Integer.MIN_VALUE; | |
} | |
} | |
} |
È inoltre possibile salvare il documento con il codice a barre caricato o appena inserito in formati di pagina fissi come PDF, XPS, ecc. L’esempio di codice seguente mostra come salvare un documento Word in formato PDF:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git. | |
Document doc = new Document(getMyDir() + "Document.docx"); | |
doc.save(getArtifactsDir() + "BaseConversions.DocxToPdf.pdf"); |
Specificare le opzioni del codice a barre
Quando si lavora con i codici a barre, è possibile impostare alcune proprietà aggiuntive. Aspose.Words fornisce la classe BarcodeParameters - classe per i parametri del codice a barre da passare a BarcodeGenerator.
Aspose.Words supporta una risoluzione incorporata di 96 ppi per le immagini generate con IBarcodeGenerator, che limita la dimensione minima di un’immagine con codice a barre. Per risolvere questo problema, gli sviluppatori possono inserire manualmente le immagini del codice a barre con la risoluzione di destinazione in un documento Word e salvarle nel formato richiesto. Per ulteriori dettagli ed esempi sull’utilizzo dei codici a barre, vedere l’articolo Leggere i codici a barre da documenti Word.