2015-12-16 91 views
0

我利用iText創建一個PDF條形碼使用相同的格式,這樣一個改變字體:對PDF旋轉文本

Barcode

的問題是左數第一個零個數字必須要小一些,而其餘的數字也要大膽。 「T.T.C.」也必須更小(不一定要在另一條線上)。 我可以用下面的代碼旋轉數:

String price = "23000 T.T.C."; 
PdfContentByte cb = docWriter.getDirectContent(); 
PdfTemplate textTemplate = cb.createTemplate(50, 50); 
ColumnText columnText = new ColumnText(textTemplate); 
columnText.setSimpleColumn(0, 0, 50, 50); 
columnText.addElement(new Paragraph(price)); 
columnText.go(); 
Image image; 
image = Image.getInstance(textTemplate); 
image.setAlignment(Image.MIDDLE); 
image.setRotationDegrees(90); 
doc.add(image); 

的問題是,我不能找到一種方法在網上更改字符串價格的某些字符的字體時,它被印在PDF。

+0

爲什麼不把它變成兩個字符串? – Nitek

+0

另外:你爲什麼使用'RUN_DIRECTION_RTL'。如果你想在你的文本中顯示阿拉伯文或希伯來文,這纔有意義。爲什麼你在問題的主題中提到HTML?爲什麼主題行不提條形碼?總而言之,這是一個非常奇怪的問題。 –

+0

@Nitek添加三個*字符串需要協調和定位,我必須考慮到這個數字可能有3個零或更少/更多,以及2個數字後面或更少/更多,我不認爲我可以考慮到所有的可能性。 – Elio

回答

2

我創建概念的小證明,結果在一個PDF,看起來像這樣:

enter image description here

正如你所看到的,它在不同尺寸和樣式的文本。它也有一個旋轉的條形碼。

看看在RotatedText例如:

public void createPdf(String dest) throws IOException, DocumentException { 
    // step 1 
    Document document = new Document(new Rectangle(60, 120), 5, 5, 5, 5); 
    // step 2 
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest)); 
    // step 3 
    document.open(); 
    // step 4 
    PdfContentByte canvas = writer.getDirectContent(); 

    Font big_bold = new Font(FontFamily.HELVETICA, 12, Font.BOLD); 
    Font small_bold = new Font(FontFamily.HELVETICA, 6, Font.BOLD); 
    Font regular = new Font(FontFamily.HELVETICA, 6); 
    Paragraph p1 = new Paragraph(); 
    p1.add(new Chunk("23", big_bold)); 
    p1.add(new Chunk("000", small_bold)); 
    document.add(p1); 

    Paragraph p2 = new Paragraph("T.T.C.", regular); 
    p2.setAlignment(Element.ALIGN_RIGHT); 
    document.add(p2); 

    BarcodeEAN barcode = new BarcodeEAN(); 
    barcode.setCodeType(Barcode.EAN8); 
    barcode.setCode("12345678"); 
    Rectangle rect = barcode.getBarcodeSize(); 
    PdfTemplate template = canvas.createTemplate(rect.getWidth(), rect.getHeight() + 10); 
    ColumnText.showTextAligned(template, Element.ALIGN_LEFT, 
      new Phrase("DARK GRAY", regular), 0, rect.getHeight() + 2, 0); 
    barcode.placeBarcode(template, BaseColor.BLACK, BaseColor.BLACK); 
    Image image = Image.getInstance(template); 
    image.setRotationDegrees(90); 
    document.add(image); 

    Paragraph p3 = new Paragraph("SMALL", regular); 
    p3.setAlignment(Element.ALIGN_CENTER); 
    document.add(p3); 

    // step 5 
    document.close(); 
} 

這個例子可以解決你所有的問題:

  • 你想要一個Paragraph使用不同的字體:使用不同的Chunk對象組成一個Paragraph
  • 您要添加上的條形碼上方多餘的文字:條形碼添加到PdfTemplate並添加使用ColumnText.showTextAligned()多餘的文字(不說你也可以撰寫Phrase使用不同Chunk對象,如果你需要一個以上的字體在額外的文本中)。
  • 您想要旋轉條形碼:將PdfTemplate包裝在Image對象內並旋轉圖像。

您可以檢查結果:rotated_text.pdf

我希望這有助於。

+0

感謝布魯諾,這正是我需要大拇指! – Elio