Ejemplo n.º 1
0
 /**
  * A set-OCG-state action (PDF 1.5) sets the state of one or more optional content groups.
  *
  * @param state an array consisting of any number of sequences beginning with a <CODE>PdfName
  *     </CODE> or <CODE>String</CODE> (ON, OFF, or Toggle) followed by one or more optional
  *     content group dictionaries <CODE>PdfLayer</CODE> or a <CODE>PdfIndirectReference</CODE> to
  *     a <CODE>PdfLayer</CODE>.<br>
  *     The array elements are processed from left to right; each name is applied to the subsequent
  *     groups until the next name is encountered:
  *     <ul>
  *       <li>ON sets the state of subsequent groups to ON
  *       <li>OFF sets the state of subsequent groups to OFF
  *       <li>Toggle reverses the state of subsequent groups
  *     </ul>
  *
  * @param preserveRB if <CODE>true</CODE>, indicates that radio-button state relationships between
  *     optional content groups (as specified by the RBGroups entry in the current configuration
  *     dictionary) should be preserved when the states in the <CODE>state</CODE> array are
  *     applied. That is, if a group is set to ON (either by ON or Toggle) during processing of the
  *     <CODE>state</CODE> array, any other groups belong to the same radio-button group are turned
  *     OFF. If a group is set to OFF, there is no effect on other groups.<br>
  *     If <CODE>false</CODE>, radio-button state relationships, if any, are ignored
  * @return the action
  */
 public static PdfAction setOCGstate(ArrayList<Object> state, boolean preserveRB) {
   PdfAction action = new PdfAction();
   action.put(PdfName.S, PdfName.SETOCGSTATE);
   PdfArray a = new PdfArray();
   for (int k = 0; k < state.size(); ++k) {
     Object o = state.get(k);
     if (o == null) continue;
     if (o instanceof PdfIndirectReference) a.add((PdfIndirectReference) o);
     else if (o instanceof PdfLayer) a.add(((PdfLayer) o).getRef());
     else if (o instanceof PdfName) a.add((PdfName) o);
     else if (o instanceof String) {
       PdfName name = null;
       String s = (String) o;
       if (s.equalsIgnoreCase("on")) name = PdfName.ON;
       else if (s.equalsIgnoreCase("off")) name = PdfName.OFF;
       else if (s.equalsIgnoreCase("toggle")) name = PdfName.TOGGLE;
       else
         throw new IllegalArgumentException(
             MessageLocalization.getComposedMessage(
                 "a.string.1.was.passed.in.state.only.on.off.and.toggle.are.allowed", s));
       a.add(name);
     } else
       throw new IllegalArgumentException(
           MessageLocalization.getComposedMessage(
               "invalid.type.was.passed.in.state.1", o.getClass().getName()));
   }
   action.put(PdfName.STATE, a);
   if (!preserveRB) action.put(PdfName.PRESERVERB, PdfBoolean.PDFFALSE);
   return action;
 }
Ejemplo n.º 2
0
 void addDocument(PdfReader reader) throws DocumentException, IOException {
   if (!reader.isOpenedWithFullPermissions())
     throw new BadPasswordException(
         MessageLocalization.getComposedMessage("pdfreader.not.opened.with.owner.password"));
   openDoc();
   if (readers2intrefs.containsKey(reader)) {
     reader = new PdfReader(reader);
   } else {
     if (reader.isTampered())
       throw new DocumentException(
           MessageLocalization.getComposedMessage("the.document.was.reused"));
     reader.consolidateNamedDestinations();
     reader.setTampered(true);
   }
   reader.shuffleSubsetNames();
   readers2intrefs.put(reader, new IntHashtable());
   readers.add(reader);
   int len = reader.getNumberOfPages();
   IntHashtable refs = new IntHashtable();
   for (int p = 1; p <= len; ++p) {
     refs.put(reader.getPageOrigRef(p).getNumber(), 1);
     reader.releasePage(p);
   }
   pages2intrefs.put(reader, refs);
   visited.put(reader, new IntHashtable());
   AcroFields acro = reader.getAcroFields();
   // when a document with NeedAppearances is encountered, the flag is set
   // in the resulting document.
   boolean needapp = !acro.isGenerateAppearances();
   if (needapp) needAppearances = true;
   fields.add(acro);
   updateCalculationOrder(reader);
 }
Ejemplo n.º 3
0
 public PdfObject getPdfObject(PdfWriter writer) {
   PdfArray array = new PdfArray(PdfName.LAB);
   PdfDictionary dictionary = new PdfDictionary();
   if (whitePoint == null
       || whitePoint.length != 3
       || whitePoint[0] < 0.000001f
       || whitePoint[2] < 0.000001f
       || whitePoint[1] < 0.999999f
       || whitePoint[1] > 1.000001f)
     throw new RuntimeException(MessageLocalization.getComposedMessage("lab.cs.white.point"));
   dictionary.put(PdfName.WHITEPOINT, new PdfArray(whitePoint));
   if (blackPoint != null) {
     if (blackPoint.length != 3
         || blackPoint[0] < -0.000001f
         || blackPoint[1] < -0.000001f
         || blackPoint[2] < -0.000001f)
       throw new RuntimeException(MessageLocalization.getComposedMessage("lab.cs.black.point"));
     dictionary.put(PdfName.BLACKPOINT, new PdfArray(blackPoint));
   }
   if (range != null) {
     if (range.length != 4 || range[0] > range[1] || range[2] > range[3])
       throw new RuntimeException(MessageLocalization.getComposedMessage("lab.cs.range"));
     dictionary.put(PdfName.RANGE, new PdfArray(range));
   }
   array.add(dictionary);
   return array;
 }
Ejemplo n.º 4
0
 /**
  * Creates a new TrueType font addressed by Unicode characters. The font will always be embedded.
  *
  * @param ttFile the location of the font on file. The file must end in '.ttf'. The modifiers
  *     after the name are ignored.
  * @param enc the encoding to be applied to this font
  * @param emb true if the font is to be embedded in the PDF
  * @param ttfAfm the font as a <CODE>byte</CODE> array
  * @throws DocumentException the font is invalid
  * @throws IOException the font file could not be read
  */
 TrueTypeFontUnicode(String ttFile, String enc, boolean emb, byte ttfAfm[], boolean forceRead)
     throws DocumentException, IOException {
   // String nameBase = getBaseName(ttFile);
   InputStream is = new FileInputStream(ttFile);
   try {
     javaFont = Font.createFont(Font.TRUETYPE_FONT, is);
   } catch (FontFormatException e) {
     e.printStackTrace();
     throw new IOException(e);
   } finally {
     is.close();
   }
   javaFontContext = new FontRenderContext(null, false, false);
   String nameBase = getBaseName(ttFile);
   String ttcName = getTTCName(nameBase);
   if (nameBase.length() < ttFile.length()) {
     style = ttFile.substring(nameBase.length());
   }
   encoding = enc;
   embedded = emb;
   fileName = ttcName;
   ttcIndex = "";
   if (ttcName.length() < nameBase.length()) ttcIndex = nameBase.substring(ttcName.length() + 1);
   fontType = FONT_TYPE_TTUNI;
   if ((fileName.toLowerCase().endsWith(".ttf")
           || fileName.toLowerCase().endsWith(".otf")
           || fileName.toLowerCase().endsWith(".ttc"))
       && (enc.equals(IDENTITY_H) || enc.equals(IDENTITY_V))
       && emb) {
     process(ttfAfm, forceRead);
     if (os_2.fsType == 2)
       throw new DocumentException(
           MessageLocalization.getComposedMessage(
               "1.cannot.be.embedded.due.to.licensing.restrictions", fileName + style));
     // Sivan
     if (cmap31 == null && !fontSpecific || cmap10 == null && fontSpecific)
       directTextToByte = true;
     // throw new
     // DocumentException(MessageLocalization.getComposedMessage("1.2.does.not.contain.an.usable.cmap", fileName, style));
     if (fontSpecific) {
       fontSpecific = false;
       String tempEncoding = encoding;
       encoding = "";
       createEncoding();
       encoding = tempEncoding;
       fontSpecific = true;
     }
   } else
     throw new DocumentException(
         MessageLocalization.getComposedMessage("1.2.is.not.a.ttf.font.file", fileName, style));
   vertical = enc.endsWith("V");
 }
Ejemplo n.º 5
0
 public static void checkCompatibleColors(BaseColor c1, BaseColor c2) {
   int type1 = ExtendedColor.getType(c1);
   int type2 = ExtendedColor.getType(c2);
   if (type1 != type2)
     throw new IllegalArgumentException(
         MessageLocalization.getComposedMessage("both.colors.must.be.of.the.same.type"));
   if (type1 == ExtendedColor.TYPE_SEPARATION
       && ((SpotColor) c1).getPdfSpotColor() != ((SpotColor) c2).getPdfSpotColor())
     throw new IllegalArgumentException(
         MessageLocalization.getComposedMessage(
             "the.spot.color.must.be.the.same.only.the.tint.can.vary"));
   if (type1 == ExtendedColor.TYPE_PATTERN || type1 == ExtendedColor.TYPE_SHADING)
     throwColorSpaceError();
 }
Ejemplo n.º 6
0
 public void setSize(int size) {
   if (size > count || size < 0)
     throw new IndexOutOfBoundsException(
         MessageLocalization.getComposedMessage(
             "the.new.size.must.be.positive.and.lt.eq.of.the.current.size"));
   count = size;
 }
Ejemplo n.º 7
0
 public void jp2_read_boxhdr() throws IOException {
   boxLength = cio_read(4);
   boxType = cio_read(4);
   if (boxLength == 1) {
     if (cio_read(4) != 0) {
       throw new IOException(
           MessageLocalization.getComposedMessage("cannot.handle.box.sizes.higher.than.2.32"));
     }
     boxLength = cio_read(4);
     if (boxLength == 0)
       throw new IOException(
           MessageLocalization.getComposedMessage("unsupported.box.size.eq.eq.0"));
   } else if (boxLength == 0) {
     throw new IOException(MessageLocalization.getComposedMessage("unsupported.box.size.eq.eq.0"));
   }
 }
Ejemplo n.º 8
0
 /**
  * Sets the rotation of the cell. Possible values are 0, 90, 180 and 270.
  *
  * @param rotation the rotation of the cell
  */
 public void setRotation(int rotation) {
   rotation %= 360;
   if (rotation < 0) rotation += 360;
   if (rotation % 90 != 0)
     throw new IllegalArgumentException(
         MessageLocalization.getComposedMessage("rotation.must.be.a.multiple.of.90"));
   this.rotation = rotation;
 }
Ejemplo n.º 9
0
 public void addImage(
     Image image, float a, float b, float c, float d, float e, float f, boolean inlineImage)
     throws DocumentException {
   if (!colorized && (!image.isMask() || !(image.getBpc() == 1 || image.getBpc() > 0xff)))
     throw new DocumentException(
         MessageLocalization.getComposedMessage(
             "not.colorized.typed3.fonts.only.accept.mask.images"));
   super.addImage(image, a, b, c, d, e, f, inlineImage);
 }
Ejemplo n.º 10
0
 public PdfLabColor(float[] whitePoint) {
   if (whitePoint == null
       || whitePoint.length != 3
       || whitePoint[0] < 0.000001f
       || whitePoint[2] < 0.000001f
       || whitePoint[1] < 0.999999f
       || whitePoint[1] > 1.000001f)
     throw new RuntimeException(MessageLocalization.getComposedMessage("lab.cs.white.point"));
   this.whitePoint = whitePoint;
 }
Ejemplo n.º 11
0
 void addDocument(PdfReader reader, List<Integer> pagesToKeep)
     throws DocumentException, IOException {
   if (!readers2intrefs.containsKey(reader) && reader.isTampered())
     throw new DocumentException(
         MessageLocalization.getComposedMessage("the.document.was.reused"));
   reader = new PdfReader(reader);
   reader.selectPages(pagesToKeep);
   if (reader.getNumberOfPages() == 0) return;
   reader.setTampered(false);
   addDocument(reader);
 }
Ejemplo n.º 12
0
 /**
  * Calculates the checksum.
  *
  * @param text the text
  * @return the checksum
  */
 static char getChecksum(String text) {
   int chk = 0;
   for (int k = 0; k < text.length(); ++k) {
     int idx = CHARS.indexOf(text.charAt(k));
     if (idx < 0)
       throw new IllegalArgumentException(
           MessageLocalization.getComposedMessage(
               "the.character.1.is.illegal.in.code.39", text.charAt(k)));
     chk += idx;
   }
   return CHARS.charAt(chk % 43);
 }
Ejemplo n.º 13
0
 /**
  * Adds or replaces a page label.
  *
  * @param page the real page to start the numbering. First page is 1
  * @param numberStyle the numbering style such as LOWERCASE_ROMAN_NUMERALS
  * @param text the text to prefix the number. Can be <CODE>null</CODE> or empty
  * @param firstPage the first logical page number
  */
 public void addPageLabel(int page, int numberStyle, String text, int firstPage) {
   if (page < 1 || firstPage < 1)
     throw new IllegalArgumentException(
         MessageLocalization.getComposedMessage(
             "in.a.page.label.the.page.numbers.must.be.greater.or.equal.to.1"));
   PdfDictionary dic = new PdfDictionary();
   if (numberStyle >= 0 && numberStyle < numberingStyle.length)
     dic.put(PdfName.S, numberingStyle[numberStyle]);
   if (text != null) dic.put(PdfName.P, new PdfString(text, PdfObject.TEXT_UNICODE));
   if (firstPage != 1) dic.put(PdfName.ST, new PdfNumber(firstPage));
   map.put(Integer.valueOf(page - 1), dic);
 }
Ejemplo n.º 14
0
 /**
  * Creates the bars.
  *
  * @param text the text to create the bars. This text does not include the start and stop
  *     characters
  * @return the bars
  */
 public static byte[] getBarsCode39(String text) {
   text = "*" + text + "*";
   byte bars[] = new byte[text.length() * 10 - 1];
   for (int k = 0; k < text.length(); ++k) {
     int idx = CHARS.indexOf(text.charAt(k));
     if (idx < 0)
       throw new IllegalArgumentException(
           MessageLocalization.getComposedMessage(
               "the.character.1.is.illegal.in.code.39", text.charAt(k)));
     System.arraycopy(BARS[idx], 0, bars, k * 10, 9);
   }
   return bars;
 }
Ejemplo n.º 15
0
 private void encodeSequence(byte seqs[], char cid) {
   int size = seqs.length - 1;
   int nextPlane = 0;
   for (int idx = 0; idx < size; ++idx) {
     char plane[] = planes.get(nextPlane);
     int one = seqs[idx] & 0xff;
     char c = plane[one];
     if (c != 0 && (c & 0x8000) == 0)
       throw new RuntimeException(MessageLocalization.getComposedMessage("inconsistent.mapping"));
     if (c == 0) {
       planes.add(new char[256]);
       c = (char) (planes.size() - 1 | 0x8000);
       plane[one] = c;
     }
     nextPlane = c & 0x7fff;
   }
   char plane[] = planes.get(nextPlane);
   int one = seqs[size] & 0xff;
   char c = plane[one];
   if ((c & 0x8000) != 0)
     throw new RuntimeException(MessageLocalization.getComposedMessage("inconsistent.mapping"));
   plane[one] = cid;
 }
Ejemplo n.º 16
0
 static PdfArray buildArray(Object names[]) {
   PdfArray array = new PdfArray();
   for (int k = 0; k < names.length; ++k) {
     Object obj = names[k];
     if (obj instanceof String) array.add(new PdfString((String) obj));
     else if (obj instanceof PdfAnnotation)
       array.add(((PdfAnnotation) obj).getIndirectReference());
     else
       throw new RuntimeException(
           MessageLocalization.getComposedMessage(
               "the.array.must.contain.string.or.pdfannotation"));
   }
   return array;
 }
Ejemplo n.º 17
0
 /**
  * Converts the extended text into a normal, escaped text, ready to generate bars.
  *
  * @param text the extended text
  * @return the escaped text
  */
 public static String getCode39Ex(String text) {
   StringBuilder out = new StringBuilder("");
   for (int k = 0; k < text.length(); ++k) {
     char c = text.charAt(k);
     if (c > 127)
       throw new IllegalArgumentException(
           MessageLocalization.getComposedMessage(
               "the.character.1.is.illegal.in.code.39.extended", c));
     char c1 = EXTENDED.charAt(c * 2);
     char c2 = EXTENDED.charAt(c * 2 + 1);
     if (c1 != ' ') out.append(c1);
     out.append(c2);
   }
   return out.toString();
 }
Ejemplo n.º 18
0
  private void readPalette(int sizeOfPalette) throws IOException {
    if (sizeOfPalette == 0) {
      return;
    }

    palette = new byte[sizeOfPalette];
    int bytesRead = 0;
    while (bytesRead < sizeOfPalette) {
      int r = inputStream.read(palette, bytesRead, sizeOfPalette - bytesRead);
      if (r < 0) {
        throw new RuntimeException(MessageLocalization.getComposedMessage("incomplete.palette"));
      }
      bytesRead += r;
    }
    properties.put("palette", palette);
  }
Ejemplo n.º 19
0
 private void openpfm() throws IOException {
   in.seek(0);
   vers = in.readShortLE();
   h_len = in.readIntLE();
   copyright = readString(60);
   type = in.readShortLE();
   points = in.readShortLE();
   verres = in.readShortLE();
   horres = in.readShortLE();
   ascent = in.readShortLE();
   intleading = in.readShortLE();
   extleading = in.readShortLE();
   italic = (byte) in.read();
   uline = (byte) in.read();
   overs = (byte) in.read();
   weight = in.readShortLE();
   charset = (byte) in.read();
   pixwidth = in.readShortLE();
   pixheight = in.readShortLE();
   kind = (byte) in.read();
   avgwidth = in.readShortLE();
   maxwidth = in.readShortLE();
   firstchar = in.read();
   lastchar = in.read();
   defchar = (byte) in.read();
   brkchar = (byte) in.read();
   widthby = in.readShortLE();
   device = in.readIntLE();
   face = in.readIntLE();
   bits = in.readIntLE();
   bitoff = in.readIntLE();
   extlen = in.readShortLE();
   psext = in.readIntLE();
   chartab = in.readIntLE();
   res1 = in.readIntLE();
   kernpairs = in.readIntLE();
   res2 = in.readIntLE();
   fontname = in.readIntLE();
   if (h_len != in.length() || extlen != 30 || fontname < 75 || fontname > 512)
     throw new IOException(MessageLocalization.getComposedMessage("not.a.valid.pfm.file"));
   in.seek(psext + 14);
   capheight = in.readShortLE();
   xheight = in.readShortLE();
   ascender = in.readShortLE();
   descender = in.readShortLE();
 }
Ejemplo n.º 20
0
 void propagate(PdfObject obj, PdfIndirectReference refo, boolean restricted) throws IOException {
   if (obj == null) return;
   //        if (refo != null)
   //            addToBody(obj, refo);
   if (obj instanceof PdfIndirectReference) return;
   switch (obj.type()) {
     case PdfObject.DICTIONARY:
     case PdfObject.STREAM:
       {
         PdfDictionary dic = (PdfDictionary) obj;
         for (PdfName key : dic.getKeys()) {
           if (restricted && (key.equals(PdfName.PARENT) || key.equals(PdfName.KIDS))) continue;
           PdfObject ob = dic.get(key);
           if (ob != null && ob.isIndirect()) {
             PRIndirectReference ind = (PRIndirectReference) ob;
             if (!setVisited(ind) && !isPage(ind)) {
               PdfIndirectReference ref = getNewReference(ind);
               propagate(PdfReader.getPdfObjectRelease(ind), ref, restricted);
             }
           } else propagate(ob, null, restricted);
         }
         break;
       }
     case PdfObject.ARRAY:
       {
         // PdfArray arr = new PdfArray();
         for (Iterator<PdfObject> it = ((PdfArray) obj).listIterator(); it.hasNext(); ) {
           PdfObject ob = it.next();
           if (ob != null && ob.isIndirect()) {
             PRIndirectReference ind = (PRIndirectReference) ob;
             if (!isVisited(ind) && !isPage(ind)) {
               PdfIndirectReference ref = getNewReference(ind);
               propagate(PdfReader.getPdfObjectRelease(ind), ref, restricted);
             }
           } else propagate(ob, null, restricted);
         }
         break;
       }
     case PdfObject.INDIRECT:
       {
         throw new RuntimeException(
             MessageLocalization.getComposedMessage("reference.pointing.to.reference"));
       }
   }
 }
Ejemplo n.º 21
0
 /**
  * This method checks if the image is a valid WMF and processes some parameters.
  *
  * @throws BadElementException
  * @throws IOException
  */
 private void processParameters() throws BadElementException, IOException {
   type = IMGTEMPLATE;
   originalType = ORIGINAL_WMF;
   InputStream is = null;
   try {
     String errorID;
     if (rawData == null) {
       is = url.openStream();
       errorID = url.toString();
     } else {
       is = new java.io.ByteArrayInputStream(rawData);
       errorID = "Byte array";
     }
     InputMeta in = new InputMeta(is);
     if (in.readInt() != 0x9AC6CDD7) {
       throw new BadElementException(
           MessageLocalization.getComposedMessage(
               "1.is.not.a.valid.placeable.windows.metafile", errorID));
     }
     in.readWord();
     int left = in.readShort();
     int top = in.readShort();
     int right = in.readShort();
     int bottom = in.readShort();
     int inch = in.readWord();
     dpiX = 72;
     dpiY = 72;
     scaledHeight = (float) (bottom - top) / inch * 72f;
     setTop(scaledHeight);
     scaledWidth = (float) (right - left) / inch * 72f;
     setRight(scaledWidth);
   } finally {
     if (is != null) {
       is.close();
     }
     plainWidth = getWidth();
     plainHeight = getHeight();
   }
 }
Ejemplo n.º 22
0
 /**
  * Implements name actions. The action can be FIRSTPAGE, LASTPAGE, NEXTPAGE, PREVPAGE and
  * PRINTDIALOG.
  *
  * @param named the named action
  */
 public PdfAction(int named) {
   put(PdfName.S, PdfName.NAMED);
   switch (named) {
     case FIRSTPAGE:
       put(PdfName.N, PdfName.FIRSTPAGE);
       break;
     case LASTPAGE:
       put(PdfName.N, PdfName.LASTPAGE);
       break;
     case NEXTPAGE:
       put(PdfName.N, PdfName.NEXTPAGE);
       break;
     case PREVPAGE:
       put(PdfName.N, PdfName.PREVPAGE);
       break;
     case PRINTDIALOG:
       put(PdfName.S, PdfName.JAVASCRIPT);
       put(PdfName.JS, new PdfString("this.print(true);\r"));
       break;
     default:
       throw new RuntimeException(MessageLocalization.getComposedMessage("invalid.named.action"));
   }
 }
Ejemplo n.º 23
0
  protected void process(InputStream stream, boolean noHeader) throws IOException {
    if (noHeader || stream instanceof BufferedInputStream) {
      inputStream = stream;
    } else {
      inputStream = new BufferedInputStream(stream);
    }
    if (!noHeader) {
      // Start File Header
      if (!(readUnsignedByte(inputStream) == 'B' && readUnsignedByte(inputStream) == 'M')) {
        throw new RuntimeException(
            MessageLocalization.getComposedMessage("invalid.magic.value.for.bmp.file"));
      }

      // Read file size
      bitmapFileSize = readDWord(inputStream);

      // Read the two reserved fields
      readWord(inputStream);
      readWord(inputStream);

      // Offset to the bitmap from the beginning
      bitmapOffset = readDWord(inputStream);

      // End File Header
    }
    // Start BitmapCoreHeader
    long size = readDWord(inputStream);

    if (size == 12) {
      width = readWord(inputStream);
      height = readWord(inputStream);
    } else {
      width = readLong(inputStream);
      height = readLong(inputStream);
    }

    int planes = readWord(inputStream);
    bitsPerPixel = readWord(inputStream);

    properties.put("color_planes", Integer.valueOf(planes));
    properties.put("bits_per_pixel", Integer.valueOf(bitsPerPixel));

    // As BMP always has 3 rgb bands, except for Version 5,
    // which is bgra
    numBands = 3;
    if (bitmapOffset == 0) bitmapOffset = size;
    if (size == 12) {
      // Windows 2.x and OS/2 1.x
      properties.put("bmp_version", "BMP v. 2.x");

      // Classify the image type
      if (bitsPerPixel == 1) {
        imageType = VERSION_2_1_BIT;
      } else if (bitsPerPixel == 4) {
        imageType = VERSION_2_4_BIT;
      } else if (bitsPerPixel == 8) {
        imageType = VERSION_2_8_BIT;
      } else if (bitsPerPixel == 24) {
        imageType = VERSION_2_24_BIT;
      }

      // Read in the palette
      int numberOfEntries = (int) ((bitmapOffset - 14 - size) / 3);
      int sizeOfPalette = numberOfEntries * 3;
      if (bitmapOffset == size) {
        switch (imageType) {
          case VERSION_2_1_BIT:
            sizeOfPalette = 2 * 3;
            break;
          case VERSION_2_4_BIT:
            sizeOfPalette = 16 * 3;
            break;
          case VERSION_2_8_BIT:
            sizeOfPalette = 256 * 3;
            break;
          case VERSION_2_24_BIT:
            sizeOfPalette = 0;
            break;
        }
        bitmapOffset = size + sizeOfPalette;
      }
      readPalette(sizeOfPalette);
    } else {

      compression = readDWord(inputStream);
      imageSize = readDWord(inputStream);
      xPelsPerMeter = readLong(inputStream);
      yPelsPerMeter = readLong(inputStream);
      long colorsUsed = readDWord(inputStream);
      long colorsImportant = readDWord(inputStream);

      switch ((int) compression) {
        case BI_RGB:
          properties.put("compression", "BI_RGB");
          break;

        case BI_RLE8:
          properties.put("compression", "BI_RLE8");
          break;

        case BI_RLE4:
          properties.put("compression", "BI_RLE4");
          break;

        case BI_BITFIELDS:
          properties.put("compression", "BI_BITFIELDS");
          break;
      }

      properties.put("x_pixels_per_meter", Long.valueOf(xPelsPerMeter));
      properties.put("y_pixels_per_meter", Long.valueOf(yPelsPerMeter));
      properties.put("colors_used", Long.valueOf(colorsUsed));
      properties.put("colors_important", Long.valueOf(colorsImportant));

      if (size == 40 || size == 52 || size == 56) {
        // Windows 3.x and Windows NT
        switch ((int) compression) {
          case BI_RGB: // No compression
          case BI_RLE8: // 8-bit RLE compression
          case BI_RLE4: // 4-bit RLE compression
            if (bitsPerPixel == 1) {
              imageType = VERSION_3_1_BIT;
            } else if (bitsPerPixel == 4) {
              imageType = VERSION_3_4_BIT;
            } else if (bitsPerPixel == 8) {
              imageType = VERSION_3_8_BIT;
            } else if (bitsPerPixel == 24) {
              imageType = VERSION_3_24_BIT;
            } else if (bitsPerPixel == 16) {
              imageType = VERSION_3_NT_16_BIT;
              redMask = 0x7C00;
              greenMask = 0x3E0;
              blueMask = 0x1F;
              properties.put("red_mask", Integer.valueOf(redMask));
              properties.put("green_mask", Integer.valueOf(greenMask));
              properties.put("blue_mask", Integer.valueOf(blueMask));
            } else if (bitsPerPixel == 32) {
              imageType = VERSION_3_NT_32_BIT;
              redMask = 0x00FF0000;
              greenMask = 0x0000FF00;
              blueMask = 0x000000FF;
              properties.put("red_mask", Integer.valueOf(redMask));
              properties.put("green_mask", Integer.valueOf(greenMask));
              properties.put("blue_mask", Integer.valueOf(blueMask));
            }

            // 52 and 56 byte header have mandatory R, G and B masks
            if (size >= 52) {
              redMask = (int) readDWord(inputStream);
              greenMask = (int) readDWord(inputStream);
              blueMask = (int) readDWord(inputStream);
              properties.put("red_mask", Integer.valueOf(redMask));
              properties.put("green_mask", Integer.valueOf(greenMask));
              properties.put("blue_mask", Integer.valueOf(blueMask));
            }
            // 56 byte header has mandatory alpha mask
            if (size == 56) {
              alphaMask = (int) readDWord(inputStream);
              properties.put("alpha_mask", Integer.valueOf(alphaMask));
            }

            // Read in the palette
            int numberOfEntries = (int) ((bitmapOffset - 14 - size) / 4);
            int sizeOfPalette = numberOfEntries * 4;
            if (bitmapOffset == size) {
              switch (imageType) {
                case VERSION_3_1_BIT:
                  sizeOfPalette = (int) (colorsUsed == 0 ? 2 : colorsUsed) * 4;
                  break;
                case VERSION_3_4_BIT:
                  sizeOfPalette = (int) (colorsUsed == 0 ? 16 : colorsUsed) * 4;
                  break;
                case VERSION_3_8_BIT:
                  sizeOfPalette = (int) (colorsUsed == 0 ? 256 : colorsUsed) * 4;
                  break;
                default:
                  sizeOfPalette = 0;
                  break;
              }
              bitmapOffset = size + sizeOfPalette;
            }
            readPalette(sizeOfPalette);

            properties.put("bmp_version", "BMP v. 3.x");
            break;

          case BI_BITFIELDS:
            if (bitsPerPixel == 16) {
              imageType = VERSION_3_NT_16_BIT;
            } else if (bitsPerPixel == 32) {
              imageType = VERSION_3_NT_32_BIT;
            }

            // BitsField encoding
            redMask = (int) readDWord(inputStream);
            greenMask = (int) readDWord(inputStream);
            blueMask = (int) readDWord(inputStream);

            // 56 byte header has mandatory alpha mask
            if (size == 56) {
              alphaMask = (int) readDWord(inputStream);
              properties.put("alpha_mask", Integer.valueOf(alphaMask));
            }

            properties.put("red_mask", Integer.valueOf(redMask));
            properties.put("green_mask", Integer.valueOf(greenMask));
            properties.put("blue_mask", Integer.valueOf(blueMask));

            if (colorsUsed != 0) {
              // there is a palette
              sizeOfPalette = (int) colorsUsed * 4;
              readPalette(sizeOfPalette);
            }

            properties.put("bmp_version", "BMP v. 3.x NT");
            break;

          default:
            throw new RuntimeException("Invalid compression specified in BMP file.");
        }
      } else if (size == 108) {
        // Windows 4.x BMP

        properties.put("bmp_version", "BMP v. 4.x");

        // rgb masks, valid only if comp is BI_BITFIELDS
        redMask = (int) readDWord(inputStream);
        greenMask = (int) readDWord(inputStream);
        blueMask = (int) readDWord(inputStream);
        // Only supported for 32bpp BI_RGB argb
        alphaMask = (int) readDWord(inputStream);
        long csType = readDWord(inputStream);
        int redX = readLong(inputStream);
        int redY = readLong(inputStream);
        int redZ = readLong(inputStream);
        int greenX = readLong(inputStream);
        int greenY = readLong(inputStream);
        int greenZ = readLong(inputStream);
        int blueX = readLong(inputStream);
        int blueY = readLong(inputStream);
        int blueZ = readLong(inputStream);
        long gammaRed = readDWord(inputStream);
        long gammaGreen = readDWord(inputStream);
        long gammaBlue = readDWord(inputStream);

        if (bitsPerPixel == 1) {
          imageType = VERSION_4_1_BIT;
        } else if (bitsPerPixel == 4) {
          imageType = VERSION_4_4_BIT;
        } else if (bitsPerPixel == 8) {
          imageType = VERSION_4_8_BIT;
        } else if (bitsPerPixel == 16) {
          imageType = VERSION_4_16_BIT;
          if ((int) compression == BI_RGB) {
            redMask = 0x7C00;
            greenMask = 0x3E0;
            blueMask = 0x1F;
          }
        } else if (bitsPerPixel == 24) {
          imageType = VERSION_4_24_BIT;
        } else if (bitsPerPixel == 32) {
          imageType = VERSION_4_32_BIT;
          if ((int) compression == BI_RGB) {
            redMask = 0x00FF0000;
            greenMask = 0x0000FF00;
            blueMask = 0x000000FF;
          }
        }

        properties.put("red_mask", Integer.valueOf(redMask));
        properties.put("green_mask", Integer.valueOf(greenMask));
        properties.put("blue_mask", Integer.valueOf(blueMask));
        properties.put("alpha_mask", Integer.valueOf(alphaMask));

        // Read in the palette
        int numberOfEntries = (int) ((bitmapOffset - 14 - size) / 4);
        int sizeOfPalette = numberOfEntries * 4;
        if (bitmapOffset == size) {
          switch (imageType) {
            case VERSION_4_1_BIT:
              sizeOfPalette = (int) (colorsUsed == 0 ? 2 : colorsUsed) * 4;
              break;
            case VERSION_4_4_BIT:
              sizeOfPalette = (int) (colorsUsed == 0 ? 16 : colorsUsed) * 4;
              break;
            case VERSION_4_8_BIT:
              sizeOfPalette = (int) (colorsUsed == 0 ? 256 : colorsUsed) * 4;
              break;
            default:
              sizeOfPalette = 0;
              break;
          }
          bitmapOffset = size + sizeOfPalette;
        }
        readPalette(sizeOfPalette);

        switch ((int) csType) {
          case LCS_CALIBRATED_RGB:
            // All the new fields are valid only for this case
            properties.put("color_space", "LCS_CALIBRATED_RGB");
            properties.put("redX", Integer.valueOf(redX));
            properties.put("redY", Integer.valueOf(redY));
            properties.put("redZ", Integer.valueOf(redZ));
            properties.put("greenX", Integer.valueOf(greenX));
            properties.put("greenY", Integer.valueOf(greenY));
            properties.put("greenZ", Integer.valueOf(greenZ));
            properties.put("blueX", Integer.valueOf(blueX));
            properties.put("blueY", Integer.valueOf(blueY));
            properties.put("blueZ", Integer.valueOf(blueZ));
            properties.put("gamma_red", Long.valueOf(gammaRed));
            properties.put("gamma_green", Long.valueOf(gammaGreen));
            properties.put("gamma_blue", Long.valueOf(gammaBlue));

            // break;
            throw new RuntimeException("Not implemented yet.");

          case LCS_sRGB:
            // Default Windows color space
            properties.put("color_space", "LCS_sRGB");
            break;

          case LCS_CMYK:
            properties.put("color_space", "LCS_CMYK");
            //		    break;
            throw new RuntimeException("Not implemented yet.");
        }

      } else {
        properties.put("bmp_version", "BMP v. 5.x");
        throw new RuntimeException("BMP version 5 not implemented yet.");
      }
    }

    if (height > 0) {
      // bottom up image
      isBottomUp = true;
    } else {
      // top down image
      isBottomUp = false;
      height = Math.abs(height);
    }
    // When number of bitsPerPixel is <= 8, we use IndexColorModel.
    if (bitsPerPixel == 1 || bitsPerPixel == 4 || bitsPerPixel == 8) {

      numBands = 1;

      // Create IndexColorModel from the palette.
      byte r[], g[], b[];
      int sizep;
      if (imageType == VERSION_2_1_BIT
          || imageType == VERSION_2_4_BIT
          || imageType == VERSION_2_8_BIT) {

        sizep = palette.length / 3;

        if (sizep > 256) {
          sizep = 256;
        }

        int off;
        r = new byte[sizep];
        g = new byte[sizep];
        b = new byte[sizep];
        for (int i = 0; i < sizep; i++) {
          off = 3 * i;
          b[i] = palette[off];
          g[i] = palette[off + 1];
          r[i] = palette[off + 2];
        }
      } else {
        sizep = palette.length / 4;

        if (sizep > 256) {
          sizep = 256;
        }

        int off;
        r = new byte[sizep];
        g = new byte[sizep];
        b = new byte[sizep];
        for (int i = 0; i < sizep; i++) {
          off = 4 * i;
          b[i] = palette[off];
          g[i] = palette[off + 1];
          r[i] = palette[off + 2];
        }
      }

    } else if (bitsPerPixel == 16) {
      numBands = 3;
    } else if (bitsPerPixel == 32) {
      numBands = alphaMask == 0 ? 3 : 4;

      // The number of bands in the SampleModel is determined by
      // the length of the mask array passed in.
    } else {
      numBands = 3;
    }
  }
Ejemplo n.º 24
0
 public void setMatrix(float matrix[]) {
   if (matrix.length != 6)
     throw new RuntimeException(
         MessageLocalization.getComposedMessage("the.matrix.size.must.be.6"));
   this.matrix = matrix;
 }
Ejemplo n.º 25
0
 /**
  * Business logic that checks if a certain object is in conformance with PDF/X.
  *
  * @param key the type of PDF ISO conformance that has to be checked
  * @param obj1 the object that is checked for conformance
  */
 public void checkPdfIsoConformance(int key, Object obj1) {
   if (writer == null || !writer.isPdfX()) return;
   int conf = writer.getPDFXConformance();
   switch (key) {
     case PdfIsoKeys.PDFISOKEY_COLOR:
       switch (conf) {
         case PdfWriter.PDFX1A2001:
           if (obj1 instanceof ExtendedColor) {
             ExtendedColor ec = (ExtendedColor) obj1;
             switch (ec.getType()) {
               case ExtendedColor.TYPE_CMYK:
               case ExtendedColor.TYPE_GRAY:
                 return;
               case ExtendedColor.TYPE_RGB:
                 throw new PdfXConformanceException(
                     MessageLocalization.getComposedMessage("colorspace.rgb.is.not.allowed"));
               case ExtendedColor.TYPE_SEPARATION:
                 SpotColor sc = (SpotColor) ec;
                 checkPdfIsoConformance(
                     PdfIsoKeys.PDFISOKEY_COLOR, sc.getPdfSpotColor().getAlternativeCS());
                 break;
               case ExtendedColor.TYPE_SHADING:
                 ShadingColor xc = (ShadingColor) ec;
                 checkPdfIsoConformance(
                     PdfIsoKeys.PDFISOKEY_COLOR,
                     xc.getPdfShadingPattern().getShading().getColorSpace());
                 break;
               case ExtendedColor.TYPE_PATTERN:
                 PatternColor pc = (PatternColor) ec;
                 checkPdfIsoConformance(
                     PdfIsoKeys.PDFISOKEY_COLOR, pc.getPainter().getDefaultColor());
                 break;
             }
           } else if (obj1 instanceof BaseColor)
             throw new PdfXConformanceException(
                 MessageLocalization.getComposedMessage("colorspace.rgb.is.not.allowed"));
           break;
       }
       break;
     case PdfIsoKeys.PDFISOKEY_CMYK:
       break;
     case PdfIsoKeys.PDFISOKEY_RGB:
       if (conf == PdfWriter.PDFX1A2001)
         throw new PdfXConformanceException(
             MessageLocalization.getComposedMessage("colorspace.rgb.is.not.allowed"));
       break;
     case PdfIsoKeys.PDFISOKEY_FONT:
       if (!((BaseFont) obj1).isEmbedded())
         throw new PdfXConformanceException(
             MessageLocalization.getComposedMessage(
                 "all.the.fonts.must.be.embedded.this.one.isn.t.1",
                 ((BaseFont) obj1).getPostscriptFontName()));
       break;
     case PdfIsoKeys.PDFISOKEY_IMAGE:
       PdfImage image = (PdfImage) obj1;
       if (image.get(PdfName.SMASK) != null)
         throw new PdfXConformanceException(
             MessageLocalization.getComposedMessage("the.smask.key.is.not.allowed.in.images"));
       switch (conf) {
         case PdfWriter.PDFX1A2001:
           PdfObject cs = image.get(PdfName.COLORSPACE);
           if (cs == null) return;
           if (cs.isName()) {
             if (PdfName.DEVICERGB.equals(cs))
               throw new PdfXConformanceException(
                   MessageLocalization.getComposedMessage("colorspace.rgb.is.not.allowed"));
           } else if (cs.isArray()) {
             if (PdfName.CALRGB.equals(((PdfArray) cs).getPdfObject(0)))
               throw new PdfXConformanceException(
                   MessageLocalization.getComposedMessage("colorspace.calrgb.is.not.allowed"));
           }
           break;
       }
       break;
     case PdfIsoKeys.PDFISOKEY_GSTATE:
       PdfDictionary gs = (PdfDictionary) obj1;
       // The example PdfXPdfA threw a NullPointerException because gs was null
       if (gs == null) break;
       PdfObject obj = gs.get(PdfName.BM);
       if (obj != null && !PdfGState.BM_NORMAL.equals(obj) && !PdfGState.BM_COMPATIBLE.equals(obj))
         throw new PdfXConformanceException(
             MessageLocalization.getComposedMessage("blend.mode.1.not.allowed", obj.toString()));
       obj = gs.get(PdfName.CA);
       double v = 0.0;
       if (obj != null && (v = ((PdfNumber) obj).doubleValue()) != 1.0)
         throw new PdfXConformanceException(
             MessageLocalization.getComposedMessage(
                 "transparency.is.not.allowed.ca.eq.1", String.valueOf(v)));
       obj = gs.get(PdfName.ca);
       v = 0.0;
       if (obj != null && (v = ((PdfNumber) obj).doubleValue()) != 1.0)
         throw new PdfXConformanceException(
             MessageLocalization.getComposedMessage(
                 "transparency.is.not.allowed.ca.eq.1", String.valueOf(v)));
       break;
     case PdfIsoKeys.PDFISOKEY_LAYER:
       throw new PdfXConformanceException(
           MessageLocalization.getComposedMessage("layers.are.not.allowed"));
   }
 }
Ejemplo n.º 26
0
  /**
   * This method checks if the image is a valid JPEG and processes some parameters.
   *
   * @throws IOException
   */
  private void processParameters() throws IOException {
    type = JPEG2000;
    originalType = ORIGINAL_JPEG2000;
    inp = null;
    try {
      String errorID;
      if (rawData == null) {
        inp = url.openStream();
        errorID = url.toString();
      } else {
        inp = new java.io.ByteArrayInputStream(rawData);
        errorID = "Byte array";
      }
      boxLength = cio_read(4);
      if (boxLength == 0x0000000c) {
        boxType = cio_read(4);
        if (JP2_JP != boxType) {
          throw new IOException(MessageLocalization.getComposedMessage("expected.jp.marker"));
        }
        if (0x0d0a870a != cio_read(4)) {
          throw new IOException(MessageLocalization.getComposedMessage("error.with.jp.marker"));
        }

        jp2_read_boxhdr();
        if (JP2_FTYP != boxType) {
          throw new IOException(MessageLocalization.getComposedMessage("expected.ftyp.marker"));
        }
        Utilities.skip(inp, boxLength - 8);
        jp2_read_boxhdr();
        do {
          if (JP2_JP2H != boxType) {
            if (boxType == JP2_JP2C) {
              throw new IOException(MessageLocalization.getComposedMessage("expected.jp2h.marker"));
            }
            Utilities.skip(inp, boxLength - 8);
            jp2_read_boxhdr();
          }
        } while (JP2_JP2H != boxType);
        jp2_read_boxhdr();
        if (JP2_IHDR != boxType) {
          throw new IOException(MessageLocalization.getComposedMessage("expected.ihdr.marker"));
        }
        scaledHeight = cio_read(4);
        setTop(scaledHeight);
        scaledWidth = cio_read(4);
        setRight(scaledWidth);
        bpc = -1;
      } else if (boxLength == 0xff4fff51) {
        Utilities.skip(inp, 4);
        int x1 = cio_read(4);
        int y1 = cio_read(4);
        int x0 = cio_read(4);
        int y0 = cio_read(4);
        Utilities.skip(inp, 16);
        colorspace = cio_read(2);
        bpc = 8;
        scaledHeight = y1 - y0;
        setTop(scaledHeight);
        scaledWidth = x1 - x0;
        setRight(scaledWidth);
      } else {
        throw new IOException(MessageLocalization.getComposedMessage("not.a.valid.jpeg2000.file"));
      }
    } finally {
      if (inp != null) {
        try {
          inp.close();
        } catch (Exception e) {
        }
        inp = null;
      }
    }
    plainWidth = getWidth();
    plainHeight = getHeight();
  }
Ejemplo n.º 27
0
 public static void throwColorSpaceError() {
   throw new IllegalArgumentException(
       MessageLocalization.getComposedMessage(
           "a.tiling.or.shading.pattern.cannot.be.used.as.a.color.space.in.a.shading.pattern"));
 }
Ejemplo n.º 28
0
 public void setBBox(float[] bBox) {
   if (bBox.length != 4)
     throw new IllegalArgumentException(
         MessageLocalization.getComposedMessage("bbox.must.be.a.4.element.array"));
   this.bBox = bBox;
 }